Composite Demo

In this code:

  • Employee is the Component.

  • Developer is the Leaf.

  • CompanyDirectory is the Composite.

We can add more specific types of employees (like Manager, Engineer, etc.) that would also implement the Employee interface. Similarly, we can create different types of directories (like DepartmentDirectory, TeamDirectory, etc.) that would inherit from CompanyDirectory.

Code:

package CompositePatternDemo; //Component interface Employee { void showEmployeeDetails(); }

The Employee interface defines a common operation, showEmployeeDetails(), which is to be implemented by all objects in the composition. All employees, whether they are a simple developer or a composite directory, will have this operation.

package CompositePatternDemo; import java.util.ArrayList; import java.util.List; //Composite class CompanyDirectory implements Employee { private List<Employee> employeeList = new ArrayList<Employee>(); @Override public void showEmployeeDetails() { for (Employee emp : employeeList) { emp.showEmployeeDetails(); } } public void addEmployee(Employee emp) { employeeList.add(emp); } public void removeEmployee(Employee emp) { employeeList.remove(emp); } }

The CompanyDirectory class is a composite node — it can contain both leaf nodes (like Developer) and other composite nodes (like other CompanyDirectory instances). It implements the Employee interface, and manages child Employee objects (both leaves and composites) in the employeeList.

It also provides an implementation of showEmployeeDetails(), which simply delegates the operation to all its children. When called on a CompanyDirectory, this method will print the details of all employees in the directory.

package CompositePatternDemo; //Leaf class Developer implements Employee { private String name; private long empId; private String position; public Developer(long empId, String name, String position) { this.empId = empId; this.name = name; this.position = position; } @Override public void showEmployeeDetails() { System.out.println(empId + " " + name + " " + position); } }

The Developer class is a leaf node — it can't have any children. It's one of the basic building blocks of our composition. This class implements the Employee interface and provides its own implementation of showEmployeeDetails() method.

Driver:

In our driver code, we first create two Developer instances, dev1 and dev2. We then create a CompanyDirectory instance, engDirectory, and add dev1 and dev2 to it. Finally, we call showEmployeeDetails() on engDirectory — thanks to the composite pattern, this prints the details of all employees in the directory, regardless of how many there are or how they're structured.