Implementing Composite: Components, Leaves, and Composites
You'll learn: How to structure the three key roles in the Composite Pattern to build hierarchical object trees.
The Three Roles in Composite
The Composite Pattern uses three distinct roles to create tree structures:
- Component - The common interface or abstract class that defines operations for both simple and complex objects
- Leaf - The basic building block with no children; represents individual objects at the end of branches
- Composite - A container that holds children (other Composites or Leaves) and implements operations by delegating to its children
Think of a company organizational chart: the "Employee" interface is the Component, individual contributors are Leaves, and managers (who have direct reports) are Composites.
How They Work Together
The Component declares operations like execute(), render(), or getSize() that all elements must support.
Leaves implement these operations directly—they do actual work but cannot contain children.
Composites implement the same operations but maintain a collection of child Components. When you call an operation on a Composite, it typically loops through its children and calls the same operation on each one, aggregating results.
Building the Tree
You construct hierarchies by adding Leaves and other Composites to parent Composites. The beauty is that client code treats both the same way—it just calls operations on the Component interface without knowing whether it's dealing with a single Leaf or an entire subtree.
This uniform treatment is what makes the pattern powerful: you can nest structures arbitrarily deep, and operations flow down the tree naturally.
Key Takeaway: The Composite Pattern uses three roles—Component (interface), Leaf (end node), and Composite (container)—to build tree structures where individual objects and groups are treated uniformly.