Composite
Category
Structural pattern
Problem
Compose objects into tree structures to represent part-whole hierarchies. Allows clients to treat individual objects and compositions uniformly.
Solution
- Define a common interface for both simple (leaf) and composite (branch) objects
- Composite objects delegate operations to their children
- Clients treat individual objects and compositions uniformly through the common interface
Structure
- Component: Interface for all objects in the composition (including leaves and composites)
- Leaf: Represents leaf objects in the composition; no children
- Composite: Represents composite objects; has children; delegates to them
- Client: Manipulates objects through the Component interface
Key Benefits
- Uniform treatment — Clients treat individual objects and compositions the same way
- Recursive structure — Naturally represents hierarchical/tree structures
- Easy to add new component types — New leaf and composite types are easy to add
Trade-offs
- Can make the design overly general if the hierarchy is complex
- Hard to restrict the types of components a composite can have
When to Use
- You want to represent part-whole hierarchies of objects
- You want clients to be able to ignore the difference between compositions of objects and individual objects
- The hierarchy is naturally tree-like
Examples
- Java
- Spring Framework
- File system implementations (directories can contain files and other directories)
- Django