什么是组合模式?
组合模式又叫部分整体模式,是用于把一组相似的对象当作一个单一的对象。组合模式依据树形结构来组合对象,用来表示部分以及整体层次。
简单说就是:用树结构组织对象,把多个对象当成一个对象使用。
适用场景
可以用树结构表示的业务场景,比如所有的组织结构,行政区划等等
代码实现
示例:一个公司的组织结构就是Tree结构,用组合模式展示
//示例:公司的组织架构
/**
* 员工类
*/
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;
}
@Override
public String toString() {
return ("Employee :[ Name : " + name
+ ", dept : " + dept + ", salary :"
+ salary + " ]");
}
}
/**
* 组合模式测试
*/
public class CompositePattern {
public static void main(String[] args) {
Employee ceo = new Employee("John", "CEO", 30000);
Employee headSales = new Employee("Robert", "Head Sales", 20000);
Employee headMarketing = new Employee("Michel", "Head Marketing", 20000);
Employee clerk1 = new Employee("Laura", "Marketing", 10000);
Employee clerk2 = new Employee("Bob", "Marketing", 10000);
Employee salesExecutive1 = new Employee("Richard", "Sales", 10000);
Employee salesExecutive2 = new Employee("Rob", "Sales", 10000);
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);
}
}
//输出:
//Employee :[ Name : John, dept : CEO, salary :30000 ]
//Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
//Employee :[ Name : Richard, dept : Sales, salary :10000 ]
//Employee :[ Name : Rob, dept : Sales, salary :10000 ]
//Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]
//Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
//Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
}
}
、