-
组合模式(Composite Pattern),又叫部分整体模式,适用于把一组相似的对象当作一个单一的对戏那个。组合模式依据树形结构来组合对象,用来表述部分遗迹整体层次。这种类型的设计模式属于结构型模式,它创建了对象组的树形结构;
-
这种模式创建了一个包含自己对象组的类。该类提供了修改相同对象组的方式;
-
意图:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对象和组合对象的使用具有一致性;
-
主要解决:它在我们树形结构问题中,模糊了简单元素和复杂元素的概念,客户程序可以处理像处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解偶;
-
何时使用:
-
-
如何解决:树脂和叶子实现统一接口,树枝内部组合该接口;
-
关键代码:树枝内部组合该接口,并且含有内部属性List,里面放Component;
-
应用实例:
-
-
优点:
-
-
1.高层模块调用简单;
-
2.节点自由增加;
-
缺点:
-
-
使用场景:
-
-
实战:
-
package composite;import java.util.ArrayList;
import java.util.List;/*** @author yangxin_ryan*/
public class Employee {private String name;private String dept;private int salary;private List subordinates;public Employee(String name, String dept, int salary) {this.name = name;this.dept = dept;this.salary = salary;subordinates = new ArrayList();}public void add(Employee employee) {subordinates.add(employee);}public void remove(Employee employee) {subordinates.remove(employee);}public List getSubordinates() {return subordinates;}@Overridepublic String toString() {return ("Employ :[ Name : " + name + ", dept : " + dept + ", salary :" + salary + " ]");}
}
package composite;/*** @author yangxin_ryan*/
public class CompositePatternDemo {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);}}}
}