組合模式用于需要以同樣的方式的方式處理一組對象作為單個對象。組合模式根據(jù)樹結(jié)構(gòu)組成對象,以表示部分以及整個層次結(jié)構(gòu)。這種類型的設(shè)計模式屬于結(jié)構(gòu)模式,因為此模式創(chuàng)建了一組對象的樹結(jié)構(gòu)。
此模式創(chuàng)建一個包含其自身對象的組的類。 此類提供了修改其相同對象的組的方法。
我們通過以下示例展示組合模式的使用,將演示員工組織的層次結(jié)構(gòu)。
假設(shè)有一個類Employee
,它作為復(fù)合模式操作類。 CompositePatternDemo
這是一個演示類,將使用Employee
類添加部門級別層次結(jié)構(gòu)并打印所有員工。組合模式示例結(jié)構(gòu)如下圖中所示 -
創(chuàng)建具有Employee
對象列表的Employee
類。
Employee.java
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
類來創(chuàng)建和打印員工層次結(jié)構(gòu)。
CompositePatternDemo.java
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);
//print all employees of the organization
System.out.println(CEO);
for (Employee headEmployee : CEO.getSubordinates()) {
System.out.println(headEmployee);
for (Employee employee : headEmployee.getSubordinates()) {
System.out.println(employee);
}
}
}
}
驗證輸出,執(zhí)行上面的代碼得到以下結(jié)果 -
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 ]