Composite Design Pattern

Hikmet Çakır
2 min readAug 7, 2022

--

Photo by Xavi Cabrera on Unsplash

Composite is a structural design pattern that composes objects into tree structures and work with these structures as if they were individual objects.

We often see small pieces are combined to create a composite. Additionally, these small pieces and composite structure are wanted to use in together. In this situations, we have to manage to relationship with between small pieces and composite piece. There is a complexity in here and we can use the Composite to manage this complexity.

How to Implement

  1. Declare the component interface with a list of methods that make sense for both simple and complex components.
  2. Create a leaf class to represent simple elements. A program may have multiple different leaf classes.
  3. Create a container class to represent complex elements. In this class, provide an array field for storing references to sub-elements.
  4. Define the methods for adding and removal of child elements in the container.

Example Implementation

I want to build a hierarchical structure of meals in a restaurant. Additionally, I want to explain uncertain expressions like leaf, component and container via example implementation.

Meal class is our Base Component. I defined it as an Abstract class but it can be defined as a Interface. Additionally, this is a base component for all the objects in the composition.

Hamburger and pizza are our leafs. Leafs shows default behaviour of our base component and It mustn’t contain a reference to the other objects.

Finally, Package class has leaf elements and is a container. It implements the base component methods and defines the child related operations.

I shared the codes I explained and more in GitHub. Additionally, certainly I recommend that you should practice with this structures. I coded these structures and these structures’ some test scenarios. You can check out to repository.

I used various resource for prepare this essay. I indicated in following. You can check out.

--

--

No responses yet