组合模式
目录组合模式(Composite Pattern)也叫合成模式, 有时又叫做部分-整体模式(Part-Whole) ,主要是用来描述部分与整体的关系。
将对象组合成树形结构以表示“部分-整体”的层次结构, 使得用户对单个对象和组合对象的使用具有一致性。
优点
- 高层模块调用简单 。
- 节点自由增加 。
缺点
使用场景
- 维护和展示部分-整体关系的场景, 如树形菜单、 文件和文件夹管理 。
- 从一个整体中能够独立出部分模块或功能的场景。
注意事项
只要是树形结构, 就要考虑使用组合模式, 这个一定要记住, 只要是要体现局部和整体的关系的时候, 而且这种关系还可能比较深, 考虑一下组合模式吧。
例子
- 员工类
import java.util.ArrayList;
import java.util.List;
/**
* 员工类
*
* @author admin
*/
public 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<>();
}
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 + " ]");
}
}
- 客户端、
/**
* 客户端
*
* @author admin
*/
public class Client {
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);
}
}
}
}
- 运行结果
标签:salary,组合,模式,dept,add,Employee,new,设计模式,public From: https://www.cnblogs.com/kouhao/p/17579622.htmlEmployee :[ 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 ]