Composite Design Pattern Explained
Composite lets you compose objects into tree structures and treat individual objects and compositions of objects uniformly through a shared interface.
Published November 13, 2026
The Composite pattern lets you treat single objects and groups of objects uniformly by arranging them in a tree. Folders containing files and folders are the classic example.
The concept
Leaf and composite share one interface. A composite holds children and forwards the operation to each, so client code calls the same method on any node.
Great for file systems, UI component trees, menus and organisation charts.
Tree of equals
folder: src (size = sum of children)
├─ file: a.js (10 KB)
└─ folder: lib (size = sum)
└─ file: b.js (5 KB)
Practical examples
File and folder
class File { constructor(n, s) { this.name = n; this.s = s } size() { return this.s } }
class Folder {
constructor(n, kids = []) { this.name = n; this.kids = kids }
size() { return this.kids.reduce((t, k) => t + k.size(), 0) }
}
new Folder('src', [new File('a', 10), new Folder('lib', [new File('b', 5)])]).size() // 15UI tree
<Card><Header/><List><Item/><Item/></List></Card>Recursive walk
const walk = (n) => [n.name, ...(n.kids ?? []).flatMap(walk)]Common mistakes
- Cycles in the tree.
- Leaves exposing child-management methods.
- Deep recursion on huge trees.
Key takeaways
- Uniform handling of parts and wholes.
- Tree structure with shared interface.
- Recursion does the work.
FAQ
Composite vs Decorator?
Composite aggregates many children; Decorator wraps one object.
Where is it in the DOM?
Every DOM node can contain nodes.