CLIENT / ASK
File explorer
selectedSize(entry) → entry.size()No file-or-folder branch in this caller.
Appearance
COMPOSITE / QUICK REFERENCE
Compose objects into a part–whole tree. Let clients use leaves and groups through the same contract.
THE STRUCTURE / NAME THE RESPONSIBILITIES
The client works with FileSystemEntry. A FileEntry returns its own size; a Folder asks its children through that same contract.
CLIENT / ASK
selectedSize(entry) → entry.size()No file-or-folder branch in this caller.
COMPONENT / COMMON CONTRACT
size(): numberEvery entry must return a size in bytes.
LEAF / DO THE WORK
Returns its own bytes. Has no children.
COMPOSITE / COMBINE THE WORK
Holds FileSystemEntry children. Calls each child’s size(), adds the results, and returns the sum.
children.reduce((n, child) => n + child.size(), 0)The same two implementations repeat at every level. This is a tree, not a fixed chain of four objects.
export interface FileSystemEntry {
size(): number;
}export function selectedSize(entry: FileSystemEntry): number {
return entry.size();
}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);
}
}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.
Composite combines children into a part–whole hierarchy. Decorator wraps a component to add behavior. They can share an interface, but solve different problems.