Card 02/ 08

ConceptDifficulty: Intermediate1 min

Composite Pattern Structure: The Class Diagram

Component, Leaf and Composite, where the Composite holds a list of Components.

Composite has three participants and a client: the component interface, the leaf that has no children, and the composite that holds children. This card reads their roles off the Gang of Four's class diagram, then draws one tree of objects built from those classes, which is the shape the recursion walks.

Composite participants
Each participant and its role
ParticipantRole
ComponentThe interface for every node in the tree, single or group.
LeafA node with no children, which answers operation itself.
CompositeA node that holds a list of components and answers operation by calling it on each child and combining the results.
ClientHolds a Component, and calls operation without knowing whether it is a leaf or a composite.

The line that makes the pattern is the aggregation from Composite back to Component. A composite holds components, not leaves, so it can hold another composite, and that one can hold more. The class diagram is flat, three boxes, while the objects built from it form a tree of any depth.

One tree of objects built from the three classes

A call to Root.operation() calls A, then Branch, which calls B and C before it returns. Each composite waits for its children, so the answers combine from the leaves upwards. The recursion ends because every path reaches a leaf; adding Root to Branch would make a cycle, and the call would never return. The template builds and prints exactly this tree.