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.