组合模式
描述
组合模式,又叫部分整体模式,用于把一组相似的对象按照对象关系组合为一个单一对象,其依据树形结构来组合对象。
光说概念太难理解了,举个例子,有个员工类(Employee),那么一个公司的所有人都可以用这个类的对象来表示,因为不管是首席执行官(CEO)、销售主管(headSales)、营销主管(headMarketing)或者普通的使用者(tester)和开发人员(programmer)都是员工类的具体对象,并且他们是有树形关系的,其关系如下:
那么此时,就可以把这七个相似对象组合为一个简单对象了,访问时候通过树形结构的特点来访问就可以了。
使用场景:当系统中的对象关联为树形,有层次结构时可以使用,这时候可以忽略单个对象的不同
实例
import java.util.ArrayList; import java.util.List; class Employee { private String name; private String title; private List<Employee> subordinates; public Employee(String name,String title) { this.name = name; this.title = title; 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 : "+ title +subordinates +" ]"; } } public class Main { public static void main(String[] args) { Employee CEO = new Employee("John","CEO"); Employee headSales = new Employee("Rob","Sales"); Employee headMarketing = new Employee("Mike","Marketing"); Employee programmer1 = new Employee("Lili","Programmer"); Employee programmer2 = new Employee("Bob","Programmer"); Employee tester1 = new Employee("Jack","Tester"); Employee tester2 = new Employee("Tom","Tester"); CEO.add(headSales); CEO.add(headMarketing); headSales.add(tester1); headSales.add(tester2); headMarketing.add(programmer1); headMarketing.add(programmer2); //print all employees of the organization System.out.println(CEO); for (Employee headEmployee : CEO.getSubordinates()) { System.out.println(headEmployee); for (Employee employee : headEmployee.getSubordinates()) { System.out.println(employee); } } } }
运行结果如下:
代码来源:特别感谢 w3School提供的代码和解释