组合模式:把一组相似的对象当成一个单一的对象,依据树形结构来组合对象,用来表示部分和整体层次。
举一个管理公司员工的例子:
public class Employee { private String name; private String dept; private double salary; private List<Employee> sub; public Employee(String n,String d,int s) { name = n; dept = d; salary = s; sub = new ArrayList<Employee>(); } public void add(Employee e) { sub.add(e); } public void remove(Emplyee e) { sub.remove(e); }
public List<Employee> getSub() {
return sub;
}
public String toString() { return "Name:" + name + "dept:" + depr + "salary:" + salary; } }
测试代码:
Employee CEO = new Employee("A0","CEO",30000); Employee headMarketing = new Employee("B0","Head Marketing", 20000); Employee clerk1 = new Employee("C0","Marketing",10000); Employee clerk2 = new Employee("C1","Marketing",10000); Employee headSales = new Employee("B1","Head Sales",20000); Employee sale1 = new Employee("C2","Marketing",10000); Employee sale2 = new Employee("C3","Marketing",10000); CEO.add(headMarking); //CEO管理headMarking CEO.add(headSales); // CEO管理headSales headMarking.add(clerk1); //headMarking管理两个人 headMarking.add(clerk2); headSales.add(sale1); //headSales管理两个人 headSales.add(sale2); //打印所有员工 System.out.println(CEO); for(Employee e1 : CEO.getSub()) { System.out.println(e1); for(Employee e2: e1.getSub()) { System.out.println(e2); } }
组合模式适合处理树形结构问题,如树形菜单,文件夹文件管理。