Design Pattern — Composite

Amir Raza
3 min readAug 26, 2020

--

“Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.”

Composite design pattern comes under Structural Patterns is one of the most important and usable part of design pattern. Developers, in his daily life uses this pattern in somehow but he doesn’t know that its really a Composite Design Pattern.

Let’s try to understand this pattern in a simple way.

Composite:

Simply in English, the word composite means “to be made up of several parts or elements.”

In this pattern, an object or group of objects behaves in a similar way and represents as a part-whole hierarchy.

for a quick example 1: consider an Employee object. In a company, HR or Project Manager or Accountant or Developer or Designer or Office Boy everyone is an employee, all have some common features like name, salary, role etc… but some has special features like HR have all employees records OR Accountant also have all employees so that he can generate salaries etc...

example 2: consider a HTML code, It has the same hierarchy of tag elements. html tag have multiple tags, body have multiple tags, div can have multiple tags as well as it itself can be a single element, p tag img tag is only element etc...

Moreover, Think about drawing different shapes OR applying different filters on a photo OR File system (Directories that contains files, each of which could be a directory) OR Containers/Boxes that contains items, can also contains boxes. OR

Key points for Composite Design Pattern

  1. Component — Component is nothing but an interface or an abstract class that contains methods to be shared to every child who inherits it.
  2. Leaf — Leaf is simply a single object that inherit Component.
  3. Composite — Composite is also a single object BUT has groups of Leaf and it also inherit Component.
  4. Client/User — It is nothing but a place from where objects are being manipulated. client uses the component reference for the composition of objects.

UML Diagram:

A tree like structure for composite pattern be like:
Html code hierarchy example

Code Example:

Html code generation via Composite Pattern.

1. First create a component, name it Tag

2. Now, create a Leaf object, name it HtmlElement

3. Lastly, create a Composite object, name it HtmlParentElement

This is done of the composite designing of the hierarchical in nature. now create a Client/User that uses this pattern to generate html code.

4. Finally, create a User, name it HtmlCodeGenerator

That’s it, you are done.

You can find some other examples below in my github repo where I will be managing all design pattern tutorials.

--

--