Java Design Patterns Composite Patterns

Introduction

Composite Patterns compose objects into tree structures to represent hierarchies.

The composite pattern allows us to treat individual objects and compositions of objects uniformly.

Example

import java.util.ArrayList;
import java.util.List;

interface Testable {
   public String test();
}

class Employee implements Testable {
   private String manager;
   private String deptName;
   private List<Testable> controls;

   Employee(String manager, String deptName) {
      this.manager = manager;
      this.deptName = deptName;
      controls = new ArrayList<Testable>();
   }// w  w w . ja  v a  2 s.  c  om

   public void Add(Employee teacher) {
      controls.add(teacher);
   }

   public void Remove(Employee teacher) {
      controls.remove(teacher);
   }

   public List<Testable> getControllingDepts() {
      return controls;
   }

   @Override
   public String test() {
      return (manager + " is the  " + deptName);
   }

}

public class Main {
   public static void main(String[] args) {
      Employee manager = new Employee("A", "Principal");

      Employee dev = new Employee("B", "Dev");

      Employee tester = new Employee("C", "Tester");

      Employee front = new Employee("Employee-1", "Front");
      Employee front2 = new Employee("Employee-2", "Font");

      Employee cseEmployee1 = new Employee("Employee-1", "Backend");
      Employee cseEmployee2 = new Employee("Employee-2", "Backend");
      Employee cseEmployee3 = new Employee("Employee-3", "Backend");

      manager.Add(dev);
      manager.Add(tester);

      dev.Add(front);
      dev.Add(front2);

      tester.Add(cseEmployee1);
      tester.Add(cseEmployee2);
      tester.Add(cseEmployee3);

      front.Add(null);
      front2.Add(null);

      cseEmployee1.Add(null);
      cseEmployee2.Add(null);
      cseEmployee3.Add(null);

      System.out.println(manager.test());
      List<Testable> hods = manager.getControllingDepts();
      for (int i = 0; i < hods.size(); i++) {
         System.out.println(hods.get(i).test());
      }

      List<Testable> mathEmployees = dev.getControllingDepts();
      for (int i = 0; i < mathEmployees.size(); i++) {
         System.out.println(mathEmployees.get(i).test());
      }

      List<Testable> cseEmployees = tester.getControllingDepts();
      for (int i = 0; i < cseEmployees.size(); i++) {
         System.out.println(cseEmployees.get(i).test());
      }
      tester.Remove(cseEmployee2);
      cseEmployees = tester.getControllingDepts();
      for (int i = 0; i < cseEmployees.size(); i++) {
         System.out.println(cseEmployees.get(i).test());
      }
   }
}



PreviousNext

Related