Composite Pattern Explained: Files, Folders, and Trees
Show notes for the Composite Pattern video — when to use it, real-world examples (file systems, the DOM, React trees), and a code-free mental model.
The Composite Pattern is the secret behind file systems, the browser DOM, React component trees, and every UI framework you’ve ever used. It lets you treat a single object and a group of objects through the exact same interface — call delete, getSize, or render on any node and it just works, leaf or branch.
What’s in the video (6m 41s)
- 0:00 — The Composite Design Pattern
- 0:41 — Real-world example: corporate analogy
- 2:41 — What is the Composite Pattern?
- 3:33 — How the Composite Pattern works
- 4:43 — When to use the Composite Pattern
- 5:51 — Final takeaway
Key takeaways
- One interface for one or many. Leaves (individual objects) and composites (groups of objects) implement the same interface, so callers stop branching on “is this one thing or a tree of things?”
- The “folder” trick. A folder’s
getSize()is just the sum of its children’sgetSize()— and a file’sgetSize()is its own size. Recursion handles every depth for free. - Use it when your data is naturally hierarchical. File systems, org charts, UI trees, menus. The pattern is a clean fit only when a tree actually models the domain.
- Skip it when it isn’t. Two-level “trees” are just lists. If every node type needs wildly different behavior, a shared interface becomes a leaky abstraction.
- You’ve already used it. Every
appendChildin the DOM, every nested React component, every directory listing — Composite under the hood.
Resources
- Full Design Patterns series (25 videos): YouTube playlist
- Previous episode: Bridge Pattern Explained
- Next episode: Decorator Pattern
- Source notes on GitHub: learnwithmanoj/design-patterns-simplified
- Based on: Design Patterns (Gang of Four), Head First Design Patterns (Freeman & Robson), and design-patterns-for-humans.
For more in this series, visit the #design-patterns tag page or jump to the channel uploads list for everything else.
Related posts
Bridge Pattern Explained - Kill the Class Explosion | 10/25
Bridge Pattern - the fix for class hierarchies that explode into `RedCircle`, `BlueCircle`, `RedSquare`, `BlueSquare`.
Adapter Pattern Explained - The USB Adapter of Code | 9/25
Adapter Pattern - the software version of a USB-C to USB-A dongle. When two pieces of code need to talk to each other but their interfaces don't match, Adapter…
Singleton Pattern Explained - Anti-Pattern or Essential? | 8/25
Singleton Pattern - the most controversial design pattern in software. Half the developers call it an anti-pattern, the other half use it every day. So who's right?