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) {
this.name = name;
this.dept = dept;
this.salary = salary;
subordinates = new ArrayList<>();
}

public void add(Employee employee) {
subordinates.add(employee);
}

public void remove(Employee employee) {
subordinates.remove(employee);
}

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

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

Step 2 : 

public class CompositePatternDemo {
private static void printEmployees(Employee CEO) {
System.out.println(CEO);
if (CEO.getSubordinates().size() == 0) {
return;
}
else {
for (Employee headEmployee : CEO.getSubordinates()) {
printEmployees(headEmployee);
}
}
}

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);

CEO.add(headSales);
CEO.add(headMarketing);

headSales.add(salesExecutive1);
headSales.add(salesExecutive2);

headMarketing.add(clerk1);
headMarketing.add(clerk2);

printEmployees(CEO);
}
}

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 *