Composite
Intent
Composes objects into tree structures and lets clients treat individual objects and compositions uniformly.
Problem
An order contains products and boxes, and boxes contain more boxes. Computing the total price is messy.
Solution
Leaves and containers share one interface; containers delegate to children and aggregate results.
Real-world analogy
An army: orders go from generals to divisions, to squads, to soldiers. Everyone receives an order the same way.
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1Component — Component declares operations common to simple and complex elements of the tree.
- 2Leaf — Leaf is a basic element that does the actual work.
- 3Composite — Composite (container) holds children, delegates work to them and combines the results.
- 4Client — Client works with every element through the Component interface.
Code example
Applicability
Use Composite when you need a tree-like object structure.
Use Composite when clients should treat simple and complex elements the same way.
Pros and cons
Pros
- Polymorphism and recursion over trees
- New element types without breaking code
Cons
- A common interface can become over-general
Check yourself
A file explorer must compute the size of a folder that contains files and other folders.
Saved in this browser only. Part of Structural patterns (0/7).