组合模式(Composite Pattern)

以结构化的方式,是单一对象具有树形结构,让单一对象更具有结构性。

组合模式的实例

在雇员和雇员之间都是存在上下级关系,如何用代码更直观的表达和关系与关系的操作,这是一个棘手的问题。

但通过组合模式,将关系表达为树状结构将更方便更直观的表达,如下。

  1. class Employee {
  2. constructor(name, dept, sal) {
  3. this.name = name;
  4. this.dept = dept;
  5. this.salary = sal;
  6. this.subordinates = [];
  7. }
  8. add(employee) {
  9. this.subordinates.push(employee);
  10. }
  11. remove(employee) {
  12. this.subordinates.splice(this.subordinates.indexOf(employee),1);
  13. }
  14. getSubordinates(){
  15. return this.subordinates;
  16. }
  17. toString(){
  18. return ("Employee :[ Name : "+ this.name
  19. +", dept : "+ this.dept + ", salary :"
  20. + this.salary+" ]");
  21. }
  22. }

所以当我们添加雇员和关系的时候将更加方便的添加,而且对于一个雇员,它只需要关心和下属的关系维护,而不需要关心上级和一些间接的关系。这样会更加清晰和维护更加方便。

  1. const CEO = new Employee("John","CEO", 30000);
  2. const headSales = new Employee("Robert","Head Sales", 20000);
  3. const headMarketing = new Employee("Michel","Head Marketing", 20000);
  4. const clerk1 = new Employee("Laura","Marketing", 10000);
  5. const clerk2 = new Employee("Bob","Marketing", 10000);
  6. const salesExecutive1 = new Employee("Richard","Sales", 10000);
  7. const salesExecutive2 = new Employee("Rob","Sales", 10000);
  8. CEO.add(headSales);
  9. CEO.add(headMarketing);
  10. headSales.add(salesExecutive1);
  11. headSales.add(salesExecutive2);
  12. headMarketing.add(clerk1);
  13. headMarketing.add(clerk2);

那么我们打印来说也只要打印最高级别的上级就能实现全部打印。

  1. function printAllEmployee(employee) {
  2. for (const subEmployee of employee.getSubordinates()) {
  3. console.log(subEmployee.toString());
  4. if(subEmployee.getSubordinates().length>0) {
  5. printAllEmployee(subEmployee)
  6. }
  7. }
  8. }
  9. //打印该组织的所有员工
  10. console.log(CEO.toString());
  11. printAllEmployee(CEO)
  12. /**
  13. * output:
  14. * Employee :[ Name : John, dept : CEO, salary :30000 ]
  15. * Employee :[ Name : Robert, dept : Head Sales, salary :20000 ]
  16. * Employee :[ Name : Richard, dept : Sales, salary :10000 ]
  17. * Employee :[ Name : Rob, dept : Sales, salary :10000 ]
  18. * Employee :[ Name : Michel, dept : Head Marketing, salary :20000 ]
  19. * Employee :[ Name : Laura, dept : Marketing, salary :10000 ]
  20. * Employee :[ Name : Bob, dept : Marketing, salary :10000 ]
  21. */

组合模式的优势

让相互关联的对象产生了结构性,无论是在关系修改或者是关系直观性上,都只需要关心当前下级的关系,那么这样能更好的降低关系和关系之间的复杂度,加强单对象关系结构的可维护性。

上一页(过滤器模式)

下一页(装饰器模式)