← Back to PatternPip

COMPOSITE / THE WALKTHROUGH

From one file
to a whole tree.

Follow the problem, the maintenance cost, and the change in responsibility.

One file can answer for itself.

A file already knows its own size. The Calculate button asks it directly; there is no collection to traverse yet.

readme.txt / INPUT: 2 kB

Size has not been requested

Restart clears the displayed result. It does not change the file.

Connect the button to the operation.

const file = new FileEntry("readme", 2000);
// The Calculate button calls this handler.
function calculateFile() { return file.size(); }
// Restart example discards the displayed result; the file is unchanged.
The file supplies its own bytes · TypeScript
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);
  }
}