design patterns · structural
Composite
Composes objects into tree structures to represent part-whole hierarchies, treating individual objects and compositions uniformly.
Pattern
Overview
Intent
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Real-World Analogy
A file system - files and folders share the same interface (display, size). Folders contain other files and folders recursively.
When you have a tree structure where both individual items and groups of items should be treated the same way, Composite gives them a shared interface so client code does not need to distinguish between leaves and containers.
A Component interface defines operations for both leaves and composites. Leaf implements Component directly. Composite implements Component and holds a list of child Components. Operations recursively delegate to children.
When to use
File systems, UI component trees, organization charts, menu systems, expression trees - any recursive tree where leaves and containers share behavior.
When not to
When tree depth is always 1 (flat list) - use a simple collection instead.
Participants
Key Insights
- The key insight is uniform treatment: client calls display() on a file or a folder - same code path
- Composite is self-similar: a Composite is a Component that contains Components
- Common in UI frameworks: a Panel contains Buttons and other Panels
- Visitor pattern is often used alongside Composite to perform operations on the tree