Composite Pattern

The Composite pattern enables you to create hierarchical tree structures of varying complexity, while allowing every element in the structure to operate with a uniform interface. The Composite pattern combines objects into tree structures to represent either the whole hierarchy or a part of the hierarchy. This means the Composite pattern allows clients to treat individual objects and compositions of objects uniformly.

UML representation


The following lists the benefits of using the Composite pattern:
  • Defines class hierarchies consisting of primitive objects and composite objects
  • Makes it easier to add new kinds of components
  • Provides flexibility of structure and a manageable interface

When to Use

You should use the Composite pattern when:
  • You want to represent the whole hierarchy or a part of the hierarchy of objects.
  • You want clients to be able to ignore the difference between compositions of objects and individual objects.
  • The structure can have any level of complexity and is dynamic.