Author image

Composite Design Pattern


Difficulty:
2/5


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.


Design

  • 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, be ittraverse. Inside it, leaf objects implement the component interface functionality, whereas composites 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 to build the project.

Github

Github repository link.


0 likes