Author image

Composite Design Pattern


Join me in our quest to decipher the obscure Composite software design Pattern hieroglyphics.

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

The Composite pattern is a structural pattern which 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, an abstract 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 abstract base class objects, which can include any Leaf object or even other composite objects
  • every leaf & composite implements the abstract base class functiontraverse. Inside it, leaf objects implement the component interface functionality, whereas composites delegate or forward requests to the objects in their array.

Some implementations also provide an iterator protocol to traverse the tree of composites, but this is not necessary for our simple example here.

I used Windows and Visual Studio with C++17 to build the project.


Github repository link.