结构型-组合模式
一:概念
是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构。
简单理解为:多个具有归属关系的列表数据,组合成只有一组新的对象,原本的子数据以树形的结构融入到主数据中去。
比如:树 子类是大树/小树 大树和小树下有杨树/柏树等,把这些对象数据组合成以树对象为主的树形结构的数据,这就是组合模式。
二:代码
package com.test.mode;
import java.util.ArrayList;
import java.util.List;
/**
* 组合模式
*/
public class PatternModeTest {
public static void main(String[] args) {
//A管理B,C
//B管理D,E
//C管理F,G
Employee CEO = new Employee("John","CEO", 30000);//A
Employee headSales = new Employee("Robert","Head Sales", 20000);//B
Employee headMarketing = new Employee("Michel","Head Marketing", 20000);//C
Employee clerk1 = new Employee("Laura","Marketing", 10000);//D
Employee clerk2 = new Employee("Bob","Marketing", 10000);//E
Employee salesExecutive1 = new Employee("Richard","Sales", 10000);//F
Employee salesExecutive2 = new Employee("Rob","Sales", 10000);//G
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);
}
}
}
}
class Employee {
private String name;
private String dept;
private int salary;
private List<Employee> subordinates;
//构造函数
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+" ]");
}
}