StructuralverifiedVerified

Composite

Composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions uniformly.

Coming Soon

errorWhat Problem Does the Composite Pattern Solve?

Applications that model hierarchical data—file systems, UI component trees, organizational charts—force client code to distinguish between leaf objects and container objects. This conditional logic is duplicated wherever the tree is traversed, making it hard to extend with new node types.

check_circleHow the Composite Pattern Works

Define a common Component interface implemented by both Leaf and Composite classes. Leaves represent end nodes and implement operations directly. Composites hold a collection of children (which can be leaves or other composites) and implement operations by delegating to their children recursively. Clients use the Component interface throughout.

Composite Pattern Architecture

hourglass_empty

Rendering diagram...

Implementation by Language

lightbulb

Composite Pattern in the Real World

A company’s org chart is a composite structure. An individual employee (leaf) has a salary and a name. A department (composite) also has a name and a budget—calculated by summing the salaries of all its members, which may themselves be other departments. HR can call ‘get budget’ on the CEO’s node and the entire tree is summed recursively.

Frequently Asked Questions

helpWhen should I use Composite instead of a simple tree structure?

Use Composite when clients need to treat individual objects and groups of objects uniformly — for example, a file system where both files and folders respond to getSize(). If only the container needs special behavior, a simple tree or list is sufficient and simpler.

helpHow do I handle operations that only make sense for leaf nodes?

Two approaches: throw an error in the composite's implementation of leaf-only methods (fail fast), or use the type system to separate leaf and composite interfaces. The latter is safer but adds complexity. Choose based on how often invalid calls would occur.