Composite Pattern

Composite is a structural design pattern that is used where there is a need to treat a group of objects in a similar way as a single object. Composite pattern composes objects in term of a tree structure to represent part as well as whole hierarchy. This pattern creates a class that contains group of its own objects. This class provides ways to modify its group of same objects.

The use of Composite pattern is demonstrated via example showing employees hierarchy of an organization. Employee class acts as composite pattern actor class. CompositePatternDemo will use Employee class to add department level hierarchy and print all employees.

Composite Pattern UML Diagram

Step 1 : 

public class Employee {
private String name;
private String dept;
private int salary;

private List<Employee> subordinates;

public Employee(String name, String dept, int salary) { = name;
this.dept = dept;
this.salary = salary;
subordinates = new ArrayList<>();

public void add(Employee employee) {

public void remove(Employee employee) {

public List<Employee> getSubordinates() {
return subordinates;

public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", dept='" + dept + '\'' +
", salary=" + salary +

Step 2 : 

public class CompositePatternDemo {
private static void printEmployees(Employee CEO) {
if (CEO.getSubordinates().size() == 0) {
else {
for (Employee headEmployee : CEO.getSubordinates()) {

public static void main(String[] args) {
Employee CEO = new Employee("John", "CEO", 30000);

Employee headSales = new Employee("Robert", "Head Sales", 20000);
Employee headMarketing = new Employee("Michael", "Head Marketing", 20000);

Employee clerk1 = new Employee("Laura", "Marketing", 10000);
Employee clerk2 = new Employee("Bob", "Marketing", 10000);

Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);





The output will be : 

Employee{name='John', dept='CEO', salary=30000}
Employee{name='Robert', dept='Head Sales', salary=20000}
Employee{name='Richard', dept='Sales', salary=10000}
Employee{name='Rob', dept='Sales', salary=10000}
Employee{name='Michael', dept='Head Marketing', salary=20000}
Employee{name='Laura', dept='Marketing', salary=10000}
Employee{name='Bob', dept='Marketing', salary=10000}

Leave a Reply

Your email address will not be published. Required fields are marked *