Structural – Composite Design Pattern
August 3, 2020 1 min read

Composite is a Structural Design Pattern that is used when two child classes have a common parent class and one of those 2 classes can contain the other class and itself inside the class. For example, let’s take “a file” and “a folder”. Both are data. Therefore “Data” is the parent class. But “a folder” can have files inside it.
In composite design pattern,
- The abstract parent class (eg: Data) is called “Component”.
- The child class (eg: a file) that is smaller and contain nothing is called “Leaf”.
- The child class (eg: a folder) that can contain itself and the leaf is called “Composite”.
Let’s see an example of a program in java.

This is the interface that will be treated as a component. It declares common operations for both simple and complex objects of a composition.


“Cashier” and “Manager” both classes are leaf classes. The leaf class represents end objects of a composition. A leaf object can’t have any sub-objects. Here inside the overridden method I gave the command to print that I want as the final output.

“Directory” is the composite class. The composite class represents complex components that may have children. Composite objects usually delegate the actual work to their children. A composite object can add or remove other components (both simple or complex) to or from its child list. Therefore I created two methods “addEmployee()” and “removeEmployee()” to add and remove employees. And used ArrayList to get the employee details to a list.

Here you can see the main method that will be treated as the client. For the objects “Cashier” and “Manager” I gave the employee details. And to print the employee details I used the method “employeeDetails()”. The output will be as given below.

You can visit the below given articles to learn about creational design patterns.
Thank you.
Creational Design Patterns


