标签:
定义:将对象组合成树型结构以表示 部分-整体的层次结构,使得用户对单个对象和组合对象的使用具有一致性
类图:
代码:
public abstract class Component { public abstract void doSomething(); }
public class Composite extends Component{ private ArrayList<Component> list = new ArrayList<Component>(); public void add(Component component){ list.add(component); } public void remove(Component component){ list.remove(component); } public ArrayList<Component> getChildren(){ return list; } }
public class Leaf extends Component{ @Override public void doSomething(){ } }
1.高层模块调用简单:
一棵树机构中所有节点都是Component,局部和整体对调这来说没有任何区别。
2.节点自由增加:
缺点:
在使用时,不能面向接口编程吗,违反了依赖倒置原则
扩展
透明组合模式
类图同上,仅仅是将所有方发全部在Component中定义。子类在不需要该方法时可以抛出异常
修改后的基类:
public abstract class Component { public void doSomething(){} public abstract void add(Component component); public abstract void remove(Component component); public abstract ArrayList<Component> getChildren(); }
public class Leaf extends Component{ @Override public void doSomething(){ } @Override public void add(Component component) throws UnsupportedOperationException{ // TODO Auto-generated method stub throw new UnsupportedOperationException(); } @Override public void remove(Component component) throws UnsupportedOperationException{ // TODO Auto-generated method stub throw new UnsupportedOperationException(); } @Override public ArrayList<Component> getChildren() throws UnsupportedOperationException{ // TODO Auto-generated method stub throw new UnsupportedOperationException(); } }透明模式的好处是遵循了依赖倒置原则
如果我们想更好的实现可以设置一个节点的父节点
代码:
public abstract class Component { private Component parent = null; protected void setParent(Component parent){ this.parent = parent; } protected Component getParent(){ return parent; } public void doSomething(){} public abstract void add(Component component); public abstract void remove(Component component); public abstract ArrayList<Component> getChildren(); }
public class Composite extends Component{ private ArrayList<Component> list = new ArrayList<Component>(); public void add(Component component){ component.setParent(this); list.add(component); } public void remove(Component component){ list.remove(component); } public ArrayList<Component> getChildren(){ return list; } }这样每个对象都有其parent
标签:
原文地址:http://blog.csdn.net/renpengddxx/article/details/52134559