Composite Pattern: Tree Structures of Objects
You'll learn how the Composite pattern lets you treat individual objects and groups of objects uniformly.
What Problem Does It Solve?
Imagine you're building a file system where you have both files and folders. A folder can contain files or other folders. How do you calculate the total size of a folder? You need to sum up individual file sizes, but also recursively sum nested folders. The Composite pattern solves this by letting you treat files and folders identically—both respond to the same "get size" operation.
The Core Idea
The Composite pattern creates tree structures where:
- Leaf nodes represent individual objects (like a file)
- Composite nodes represent containers that hold leaves or other composites (like a folder)
- Both implement the same interface, so clients can treat them uniformly
Think of it like a company org chart: individual employees and entire departments both can report their headcount. An employee returns 1; a department sums its members (some of whom might manage sub-departments).
The Structure
You define a common interface with operations like operation(). Leaf classes implement it directly. Composite classes also implement it, but delegate to their children—iterating through a collection of child components and calling operation() on each.
This creates a part-whole hierarchy where the whole (composite) contains parts (leaves or other composites), and you can work with any level uniformly.
Key Takeaway: The Composite pattern lets you build tree structures where individual objects and compositions of objects share a common interface, enabling uniform treatment and recursive operations across the hierarchy.