组合模式(Composite Pattern)
组合模式主要是应对这样的问题:一类具有“容器特征”的对象 —— 即他们在充当对象的同时,又是其他对象的容器的情况。将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得客户对单个对象和组合对象的使用具有一致性。
?
想到Composite就应该想到树形结构图。
?
将“客户代码与复杂的对象容器结构”解耦是组合模式的核心思想,解耦之后,客户代码将与纯粹的对象接口(而非对象容器的复杂内部实现结构)发生依赖关系,从而更能“应对变化”。
?
Component类源码:
public class Client {private static void doCircle(Component o){List list = o.getChildren();if(list!=null && list.size()>0){for(int i=0;i<list.size();i++){Component sub = (Component)list.get(i);sub.operation();//递归执行doCircle(sub);}}}public static void main(String[] args) {Component root = new Composite("树干");Component comp1 = new Composite("树枝一");Component comp2 = new Composite("树枝二");root.add(comp1);root.add(comp2);Component leaf1 = new Leaf("叶一");Component leaf2 = new Leaf("叶二");comp1.add(leaf1);comp1.add(leaf2);doCircle(root);}}
?
??