CLIENT / ASK
File explorer
selectedSize(entry) → entry.size()No file-or-folder branch in this caller.
Appearance
COMPOSITE / THE IDEA IN A MINUTE
Composite gives individual objects and groups of objects the same operation. A group delegates to its children—even when those children are more groups.
Think of a file explorer: a file has a size. A folder has a size too, calculated from everything inside. The caller can ask either one without walking the tree itself.
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.
TRY THE IDEA / FILE EXPLORER
Calculate the size of Project, then try Assets or a single file. Folders pass size() down; numbers return up. Values are fictional file sizes (1 kB = 1,000 bytes).
2 direct children. Follow the trace to see each visited child.
Own value: 2 kB. No children to visit.
1 direct child. Follow the trace to see each visited child.
Own value: 8 kB. No children to visit.
Expand a folder to inspect its children. Starting a trace opens every visited folder.
BEFORE / THE CALLER KNOWS TOO MUCH
The caller checks the type, reads a file’s bytes, or loops through a folder and repeats. This can calculate the right result, but the caller now knows every supported kind and the tree’s traversal rules.
AFTER / EACH OBJECT KNOWS ITS JOB
A file returns its bytes. A folder adds up its children’s sizes. The caller uses one contract. Nesting another folder does not change that caller or the existing folder logic.
Folders, nested UI groups, menus and packaged products can share an operation across individuals and collections. The benefit grows when clients should treat them uniformly.
A flat list may need only a loop. Not every leaf can support adding children; keep child management on groups. Cycles and shared references need an explicit policy—this lesson builds a finite tree.
Start with one file, expose the caller’s type checks, then move traversal into folders.
Three chapters · a leaf, a growing tree, one contractBACK FOR A REFRESHERRecall the roles, recursive call and tradeoffs without replaying the lesson.
TypeScript + Kotlin · concise refresher