Compose objects into tree structures and treat individual objects and composites uniformly. You need to represent part-whole hierarchies. Clien
Composite
Overview
Compose objects into tree structures and treat individual objects and composites uniformly.
When to use
- You need to represent part-whole hierarchies.
- Clients should handle single items and groups consistently.
Java example
TypeScript example
Pros and cons
Pros:
- Simplifies client logic for trees.
- Easy to add new node types.
Cons:
- Can obscure differences between leaf and composite.
Common pitfalls
- Exposing mutation when tree should be immutable.
- Breaking invariants by mixing incompatible nodes.