We discuss the Composite pattern, which enables complicated structures of items and groupings of those items.
The Composite is a Structural Pattern.
The Composite Pattern’s intent is to compose objects into tree structures to represent part-whole hierarchies. It lets clients treat individual objects and compositions of objects uniformly.
Imagine a graphics application. We would have primitives like Line, Rectangle, Text etc, but we also want to compose them together to form more complicated shapes, like a Picture.
These composed elements must contain some extra methods like a way to access their “children”. But at the same time clients need to be able to access “graphical elements” without needing to know if they are primitives or composites.
This is done by having both primitives and composites implement the same interface or abstract class, say a “Graphic” interface. That interface will contain the methods that are shared by both primitive and composite elements. On top of that, the composite elements need to have operations for managing their children.
The Composite Pattern can work well with Iterator and Visitor, as we will see in the examples.
An important consideration is how rich to make the Component interface:
This is even more of a concern in a statically typed setting.
See composite.js