Author image

Composite Design Pattern


Here we decipher the obscure Composite Pattern hieroglyphics.

Definition: Compose objects into tree structures to represent part-whole hierarchies.

The Composite pattern enables us to iterate over objects or collection of those objects in a uniform manner, without having to typecheck or differentiate between the concrete objects and their collections. All those objects share a common interface/base class.

The whole point of the Composite pattern is that the Composite can be treated atomically as if it was a leaf object, without needing to know that there are many objects inside. Leaf objects perform a request directly, and Composite objects forward the request to their child components recursively downwards the tree structure. This makes client classes easier to implement, change, test, and reuse.


  • identify and create the concrete/leaf classes and the container (composite) classes
  • create a unified base class or interface for both part (Leaf) objects and whole (Composite) objects to inherit from. This way we'll make their use interchangeable.
  • the composite class has a vector/array of pointers to base class objects, which can be any Leaf object or even other composite objects
  • every class, leaves & composites, implements the abstract base class function, say traverse. In it leaf objects implement the component interface functionality while composite delegate or forward requests to the concrete objects in their array

Some implementations also provide an iterator protocol to traverse the tree of composites, but this is not necessary at.all .com.

I used Windows 8.1 x86_64, Visual Studio 2017, C++17 to build the project.


Github repository link.