← Back to PatternPip

COMPOSITE / QUICK REFERENCE

Individuals and groups.
One shared operation.

Compose objects into a part–whole tree. Let clients use leaves and groups through the same contract.

Component
The common operation: FileSystemEntry.size().
Leaf
FileEntry returns its own bytes. It has no children.
Composite
Folder holds entries and sums each child’s size(). A child can be another Folder.
Client
Calls entry.size() without inspecting the concrete kind.

THE STRUCTURE / NAME THE RESPONSIBILITIES

One contract. Two ways to fulfil it.

The client works with FileSystemEntry. A FileEntry returns its own size; a Folder asks its children through that same contract.

CLIENT / ASK

File explorer

selectedSize(entry) → entry.size()

No file-or-folder branch in this caller.

COMPONENT / COMMON CONTRACT

FileSystemEntry

size(): number

Every entry must return a size in bytes.

LEAF / DO THE WORK

FileEntry

Returns its own bytes. Has no children.

COMPOSITE / COMBINE THE WORK

Folder

Holds FileSystemEntry children. Calls each child’s size(), adds the results, and returns the sum.

children.reduce((n, child) => n + child.size(), 0)
Children: files or more folders

The same two implementations repeat at every level. This is a tree, not a fixed chain of four objects.

The recursive step is in the group.

Common contract

export interface FileSystemEntry {
  size(): number;
}

Uniform client

export function selectedSize(entry: FileSystemEntry): number {
  return entry.size();
}

Leaf

export class FileEntry implements FileSystemEntry {
  readonly id: string;
  readonly bytes: number;
  private readonly measure: Measure;
  constructor(id: string, bytes: number, measure: Measure = unrecorded) {
    if (!Number.isSafeInteger(bytes) || bytes < 0)
      throw new Error("Size must be a nonnegative safe integer.");
    this.id = id;
    this.bytes = bytes;
    this.measure = measure;
  }
  size(): number {
    return this.measure(this.id, () => this.bytes);
  }
}

Composite

export class Folder implements FileSystemEntry {
  readonly id: string;
  readonly children: readonly FileSystemEntry[];
  private readonly measure: Measure;
  constructor(
    id: string,
    children: readonly FileSystemEntry[],
    measure: Measure = unrecorded,
  ) {
    this.id = id;
    this.children = Object.freeze([...children]);
    this.measure = measure;
  }
  size(): number {
    return this.measure(this.id, () =>
      this.children.reduce((sum, child) => sum + child.size(), 0),
    );
  }
}

The TypeScript measure wrapper records real calls for the visualization. Kotlin shows the same model without that instrumentation.

Complete Composite example

The running file/folder model, its trace recorder and a standalone Kotlin equivalent.

Running file/folder model. The optional measure function records real calls for the animation.

Download files.ts
import {
  recordTree,
  unrecorded,
  type Measure,
  type TreeItem,
} from "./trace.ts";

// section:contract
export interface FileSystemEntry {
  size(): number;
}
// end:contract
// section:leaf
export class FileEntry implements FileSystemEntry {
  readonly id: string;
  readonly bytes: number;
  private readonly measure: Measure;
  constructor(id: string, bytes: number, measure: Measure = unrecorded) {
    if (!Number.isSafeInteger(bytes) || bytes < 0)
      throw new Error("Size must be a nonnegative safe integer.");
    this.id = id;
    this.bytes = bytes;
    this.measure = measure;
  }
  size(): number {
    return this.measure(this.id, () => this.bytes);
  }
}
// end:leaf
// section:group
export class Folder implements FileSystemEntry {
  readonly id: string;
  readonly children: readonly FileSystemEntry[];
  private readonly measure: Measure;
  constructor(
    id: string,
    children: readonly FileSystemEntry[],
    measure: Measure = unrecorded,
  ) {
    this.id = id;
    this.children = Object.freeze([...children]);
    this.measure = measure;
  }
  size(): number {
    return this.measure(this.id, () =>
      this.children.reduce((sum, child) => sum + child.size(), 0),
    );
  }
}
// end:group
// section:client
export function selectedSize(entry: FileSystemEntry): number {
  return entry.size();
}
// end:client

export type RawEntry =
  | { kind: "file"; bytes: number }
  | { kind: "folder"; children: readonly RawEntry[] };
// section:before
export function sizeInClient(entry: RawEntry): number {
  if (entry.kind === "file") return entry.bytes;
  return entry.children.reduce((sum, child) => sum + sizeInClient(child), 0);
}
// end:before
export function fileTree(extra = false, empty = false): TreeItem {
  const leaf = (id: string, label: string, amount: number): TreeItem => ({
    id,
    label,
    kind: "leaf",
    amount,
    children: [],
  });
  return {
    id: "project",
    label: "Project",
    kind: "group",
    children: empty
      ? []
      : [
          leaf("readme", "readme.txt", 2000),
          {
            id: "assets",
            label: "Assets",
            kind: "group",
            children: [
              leaf("photo", "photo.png", 8000),
              ...(extra ? [leaf("icon", "icon.svg", 3000)] : []),
            ],
          },
        ],
  };
}
export function createEntry(
  item: TreeItem,
  measure: Measure = unrecorded,
): FileSystemEntry {
  return item.kind === "leaf"
    ? new FileEntry(item.id, item.amount ?? 0, measure)
    : new Folder(
        item.id,
        item.children.map((child) => createEntry(child, measure)),
        measure,
      );
}
export function runFiles(tree: TreeItem) {
  return recordTree(tree.id, (measure) =>
    selectedSize(createEntry(tree, measure)),
  );
}

export const formatSize = (value: number) => `${value / 1000} kB`;

Kotlin compilation is unverified. All files are simulated in memory; the example does not access your filesystem.

kotlinc Files.kt -include-runtime -d files.jar
java -jar files.jar

Useful boundaries

  • Use a shared operation only when it has a meaningful result for both leaves and groups.
  • Keep child management on groups; a file does not need a fake add() method.
  • An empty folder returns zero. A new leaf implements size(); existing callers and groups stay unchanged.
  • This example copies child lists and builds a finite tree. It does not follow filesystem links, mutate a live filesystem or detect arbitrary graph cycles.
  • A shared child would be counted once per occurrence. Decide ownership, cycle handling and caching explicitly before using a general graph.
  • Without caching, size() visits each node in the subtree: O(n) time and O(depth) call stack. Very deep trees can exhaust the stack.

Composite or Decorator?

Composite combines children into a part–whole hierarchy. Decorator wraps a component to add behavior. They can share an interface, but solve different problems.