組合模式(Composite Pattern),又叫部分整體模式超升,是用于把一組相似的對象當作一個單一的對象干像。組合模式依據(jù)樹形結構來組合對象蛙埂,用來表示部分以及整體層次倦畅。這種類型的設計模式屬于結構型模式,它創(chuàng)建了對象組的樹形結構绣的。
這種模式創(chuàng)建了一個包含自己對象組的類叠赐。該類提供了修改相同對象組的方式。
優(yōu)點: 1屡江、高層模塊調(diào)用簡單芭概。 2、節(jié)點自由增加惩嘉。
缺點:在使用組合模式時罢洲,其葉子和樹枝的聲明都是實現(xiàn)類,而不是接口文黎,違反了依賴倒置原則惹苗。
關鍵代碼:樹枝內(nèi)部組合該接口,并且含有內(nèi)部屬性 List耸峭,里面放 Component桩蓉。
- 創(chuàng)建 Employee 類,該類帶有 Employee 對象的列表劳闹。
/**
* 1. 創(chuàng)建 Employee 類院究,該類帶有 Employee 對象的列表洽瞬。
* @author mazaiting
*/
public class Employee {
/**姓名*/
private String name;
/**職位*/
private String dept;
/**工資*/
private int salary;
private List<Employee> subordinates;
public Employee(String name, String dept, int salary) {
this.name = name;
this.dept = dept;
this.salary = salary;
subordinates = new ArrayList<Employee>();
}
/**
* 添加
*/
public void add(Employee e) {
subordinates.add(e);
}
/**
* 移除
*/
public void remove(Employee e) {
subordinates.remove(e);
}
/**
* 獲取數(shù)據(jù)
*/
public List<Employee> getSubordinates() {
return subordinates;
}
@Override
public String toString() {
return "Employee [name=" + name + ", dept=" + dept + ", salary="
+ salary + "]";
}
}
- 使用 Employee 類來創(chuàng)建和打印員工的層次結構。
/**
* 2. 使用 Employee 類來創(chuàng)建和打印員工的層次結構业汰。
* @author mazaiting
*/
public class Client {
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);
}
}
}
}
- 打印結果
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]