Structural Patterns Part 3/7: Composite Pattern
目录
Definition
Composite Pattern是这样一种模式:它把一系列对象组合起来,形成一个树状的结构来代表部分-整体(单个-组合)的关系,结构的每个元素都可以一视同仁,统一处理,有点递归的意思。
举个例子,在公司里,有CEO,Manager和Developer,Tester等职位。
CEO(单个)的下属是Manager(组合),Manager(单个)的下属是Developer和Tester(组合),但是对于Composite Pattern的使用者来说,不管是CEO还是Manager还是Developer还是Tester,他们都是Employee。
何时使用?当希望表示对象的部分-整体的结构时,当希望Client统一无差异的对待单个和组合对象。
使用频率: Medium High
UML Class Diagram
Implementation
把CEO, Manager以及Developer,Tester均看成Empolyee来处理。
// CompositeDemo
package designpatternsstructuralpatterns.composite;
import java.util.*;
public class CompositeDemo {
public static void main(String[] args) {
Employee CEO = new Employee("John", "CEO");
Employee mgrDev = new Employee("Robert", "Dev Mgr");
Employee mgrTest = new Employee("Michel", "Test Mgr");
Employee dev1 = new Employee("Laura", "Dev");
Employee dev2 = new Employee("Bob", "Dev");
Employee test1 = new Employee("Richard", "Tester");
Employee test2 = new Employee("Rob", "Tester");
CEO.add(mgrDev);
CEO.add(mgrTest);
mgrDev.add(dev1);
mgrDev.add(dev2);
mgrTest.add(test1);
mgrTest.add(test2);
System.out.println(CEO);
System.out.println("===============================");
for (Employee manager : CEO.getSubordinates()) {
System.out.println(manager);
for (Employee employee : manager.getSubordinates()) {
System.out.println(employee);
}
System.out.println("===============================");
}
}
}
class Employee {
private String name;
private String position;
private List<Employee> subordinates;
public Employee(String name, String position) {
this.name = name;
this.position = position;
subordinates = new ArrayList<>();
}
public boolean add(Employee e) {
return subordinates.add(e);
}
public boolean remove(Employee e) {
return subordinates.remove(e);
}
public List<Employee> getSubordinates() {
return subordinates;
}
@Override
public String toString() {
return "position: " + position + ", " + "name: " + name;
}
}
// output
position: CEO, name: John
===============================
position: Dev Mgr, name: Robert
position: Dev, name: Laura
position: Dev, name: Bob
===============================
position: Test Mgr, name: Michel
position: Tester, name: Richard
position: Tester, name: Rob
===============================