Composite Pattern

When we think of object oriented programming, we think of inheritance. But inheritance is not always the best way of attacking a problem. Inheritance should be used only when the a class inherits from the other in spirit - not because it has similar functionality.

For example, a circle is a shape. But, an idol has a shape. In its spirit, an idol has a lot more than a shape. A circle too is more than just a shape. But, in its spirit, it is just a shape. In plain English, a circle "Is a" shape, but an idol "Has a" shape. The inheritance is called an "Is a" relation while composition is "Has a" relation.

The composition pattern provides a formal definition for this composition. Here, the container class contains a reference to an interface in the hierarchy of implementing objects.


The composition pattern has four different players

  • Component - Component declares the interface for objects in the composition and for accessing and managing its child components. It also implements default behavior for the interface common to all classes as appropriate.
  • Leaf - Leaf defines behavior for primitive objects in the composition. It represents leaf objects in the composition.
  • Composite - Composite stores child components and implements child related operations in the component interface.
  • Client - Client manipulates the objects in the composition through the component interface.

The client uses the component class interface to interact with objects in the composition structure. If recipient is a leaf then request is handled directly. If recipient is a composite, then it usually forwards request to its child components, possibly performing additional operations before and after forwarding.