一、定义
将对象组合成树形结构的层次结构,树的节点或者整个结构对于调用者来说没有任何区别
二、要素
1.枝干和叶子节点的抽象类
2.枝干类
3.叶子节点类
三、代码实例
//节点和枝干抽象类
public abstract class Component { public void doSomething(){ } }//枝干
public class Composite extends Component{ private ArrayList<Component> list = new ArrayList<Component>(); public void add(Component component){ list.add(component); } public ArrayList<Component> getChilds(){ return this.list; } }//叶子节点
public class Leaf extends Component{ private String mValue; public Leaf(String value){ this.mValue = value; } public void doSomething(){ System.out.print(this.mValue+"\n"); } }//客户端
public class Client { public static void main(String[] args) { Composite root = new Composite(); Composite branch = new Composite();//枝干 Component leftLeaf = new Leaf("左叶子节点");//左叶子节点 Component rightLeaf = new Leaf("右叶子节点");//右叶子节点 branch.add(leftLeaf); branch.add(rightLeaf); root.add(branch); show(root); } public static void show(Composite root){ for(Component component : root.getChilds()){ if(component instanceof Leaf){ component.doSomething(); } else { show((Composite)component); } } } } 四、说明1.高层模块无需关心处理的是单个对象还是整个组合结构
2.枝干和叶子节点都很容易扩展,符合开闭原则