creational

Composite

Compose objects into tree structures to represent part-whole hierarchies. Treat individual and composite objects uniformly.

Tree-shaped data is everywhere — files inside folders inside folders, UI panels containing buttons and other panels, an org chart of managers and reports. The painful part is writing code that handles both the leaves and the branches, sprinkling if (isFolder) checks through every operation. Composite removes that distinction by making a container and a single item present the exact same interface.

An army — a soldier is a leaf; a squad contains soldiers; a platoon contains squads. Orders cascade down.

Key Concepts

1
Both the leaf and the composite implement one common component interface. A leaf does the real work directly; a composite holds a list of children — each of which may itself be a leaf or another composite — and implements each operation by delegating to its children and combining the results. Computing the total size of a folder, for instance, becomes a recursive sum where the folder asks each child for its size without caring whether that child is a file or a sub-folder. The recursion is implicit in the structure.
2
This is the right model for file systems, nested UI component trees, menu-and-submenu structures, graphics scene graphs, and bill-of-materials hierarchies. The tension to manage is the design of the shared interface: child-management methods like add() and remove() only make sense on composites, so you must choose between a uniform interface where leaves expose those methods and reject them at runtime, or a safer interface where only composites have them but clients must occasionally check the type. Most implementations lean toward uniformity for simplicity, accepting that a leaf's add() is a no-op or throws.
add()remove()