Implementing the Composite Pattern in Java
The composite pattern enables treatnig individual objects and compositions of objects uniformly. This structural design pattern organizes objects into a tree-like structure to represent part-whole hierarchies. It allows clients to work with individual objects and composites in the same way.
In this implementation, we create a hierarchy of employees within an organization using the composite pattern.
Implementation Example
We define an Employee class that serves as both a leaf and a composite node in the organizational structure. The CompositePatternDemo class demonstrates how to build the hierarchy and display all employees.
Step 1
Create the Employee class that maintains a list of subordinate employees.
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String fullName;
private String department;
private int compensation;
private List<Employee> directReports;
public Employee(String name, String dept, int pay) {
this.fullName = name;
this.department = dept;
this.compensation = pay;
this.directReports = new ArrayList<>();
}
public void attach(Employee subordinate) {
directReports.add(subordinate);
}
public void detach(Employee subordinate) {
directReports.remove(subordinate);
}
public List<Employee> getDirectReports() {
return directReports;
}
@Override
public String toString() {
return "Employee :[ Name : " + fullName + ", dept : " + department + ", salary :" + compensation + " ]";
}
}
Step 2
Use the Employee class to construct and display the organizational hierarchy.
public class CompositePatternDemo {
public static void main(String[] args) {
Employee chiefExecutive = new Employee("John", "CEO", 30000);
Employee salesLead = new Employee("Robert", "Head Sales", 20000);
Employee marketingLead = new Employee("Michel", "Head Marketing", 20000);
Employee marketingClerk1 = new Employee("Laura", "Marketing", 10000);
Employee marketingClerk2 = new Employee("Bob", "Marketing", 10000);
Employee salesRep1 = new Employee("Richard", "Sales", 10000);
Employee salesRep2 = new Employee("Rob", "Sales", 10000);
chiefExecutive.attach(salesLead);
chiefExecutive.attach(marketingLead);
salesLead.attach(salesRep1);
salesLead.attach(salesRep2);
marketingLead.attach(marketingClerk1);
marketingLead.attach(marketingClerk2);
System.out.println(chiefExecutive);
for (Employee manager : chiefExecutive.getDirectReports()) {
System.out.println(manager);
for (Employee staff : manager.getDirectReports()) {
System.out.println(staff);
}
}
}
}
Step 3
Execute the program to see the following output:
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 : Michel, dept : Head Marketing, salary :20000 ]
Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
Employee :[ Name : Bob, dept : Marketing, salary :10000 ]