GoF pattern • Structural
GoFStructuralJava example
Composite solves a specific structural problem in the design.
Treat individual objects and groups uniformly in tree-like structures.
Pattern overview
GoF pattern
Treat individual objects and groups uniformly in tree-like structures.
Intent
Compose objects into tree structures so clients can treat part and whole consistently.
Problem
The system manages hierarchies, but client code should not need separate branches for single nodes versus groups.
Solution
Define a common component API that both leaves and composites implement.
Fit and tradeoffs
FamilyGoF
CategoryStructural
Best used when
- When working with trees, menus, file systems, UI containers, or organization charts.
Tradeoffs
- Can make some invalid operations possible unless carefully designed.
- Leaf-only behavior may need defensive handling.
Java example
This example is intentionally compact so the pattern shape stays easy to see.
interface Task {
Duration estimate();
}
record SimpleTask(Duration estimate) implements Task {}
final class TaskGroup implements Task {
private final List<Task> children = new ArrayList<>();
void add(Task task) { children.add(task); }
@Override
public Duration estimate() {
return children.stream()
.map(Task::estimate)
.reduce(Duration.ZERO, Duration::plus);
}
}