组合模式
定义
组合模式(Composite Pattern),又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
示例
员工类
public class Employee {
private String name;
private String dept;
private List<Employee> employees = null;
public Employee(String name,String dept) {
this.name = name;
this.dept = dept;
employees = new ArrayList<Employee>();
}
public void addEmployee(Employee e){
this.employees.add(e);
}
public void delEmployee(Employee e){
this.employees.remove(e);
}
public List<Employee> getEmployee(){
return employees;
}
@Override
public String toString() {
return "{\"name\":\""+name+"\",\"dept\":\""+dept+"\",\"sub\":"+employees+"}";
}
}
测试类
public class CompositeTest {
public static void main(String[] args) {
Employee employee = new Employee("huzd", "CEO");
Employee employeeSales = new Employee("huzdSales1", "Sales");
Employee employeeMarketing = new Employee("huzdSales2", "Marketing");
Employee employeeTester1 = new Employee("huzdTester1", "Tester");
Employee employeeTester2 = new Employee("huzdTester2", "Tester");
Employee employeeProgrammer1 = new Employee("huzdProgrammer1", "Programmer");
Employee employeeProgrammer2 = new Employee("huzdProgrammer2", "Programmer");
employee.addEmployee(employeeSales);
employee.addEmployee(employeeMarketing);
employeeSales.addEmployee(employeeTester1);
employeeSales.addEmployee(employeeTester2);
employeeMarketing.addEmployee(employeeProgrammer1);
employeeMarketing.addEmployee(employeeProgrammer2);
System.out.println(employee);
}
}
分析
- 将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
- 优点 1、高层模块调用简单。 2、节点自由增加。