复合模式用于我们需要以类似方式将一组对象视为单个对象的情况。 复合模式以树结构的形式组合对象以表示部分以及整个层次结构。 这种类型的设计模式属于结构模式,因为这种模式创建了一组对象的树结构。
此模式创建一个包含一组自己的对象的类。 此类提供了修改其相同对象组的方法。
我们通过以下示例演示复合模式的使用,其中我们将展示组织的员工层次结构。
举例说明
我们有一个 Employee 类,它充当复合模式 Actor 类。 CompositePatternDemo,我们的演示类将使用 Employee 类添加部门级别的层次结构并打印所有员工。
第一步
创建一个JavaBean
import java.util.ArrayList;
import java.util.List;
public class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
// constructor
public Employee(String name,String dept, int sal) {
this.name = name;
this.dept = dept;
this.salary = sal;
subordinates = new ArrayList<Employee>();
}
public void add(Employee e) {
subordinates.add(e);
}
public void remove(Employee e) {
subordinates.remove(e);
}
public List<Employee> getSubordinates(){
return subordinates;
}
public String toString(){
return ("Employee :[ Name : " + name + ", dept : " + dept + ", salary :" + salary+" ]");
}
}
第二步
使用 Employee 类来创建和打印员工的层次结构。
public class CompositePatternDemo {
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("Michel","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);
//打印该组织的所有员工
System.out.println(CEO);
for (Employee headEmployee : CEO.getSubordinates()) {
System.out.println(headEmployee);
for (Employee employee : headEmployee.getSubordinates()) {
System.out.println(employee);
}
}
}
}