Java设计模式《十五》组合模式

来源:互联网 发布:虚拟多点定位软件 编辑:程序博客网 时间:2024/06/15 22:12
//组合模式 将对象组合成树状结构以表示 部分-整体的层次结构//组合模式使用得用户对单个对象和组合对象的使用具有一致性//需求中体现部分与整体层次的机构时//以及希望用户可以忽略组合对象与每个对象的不同 统一使用组合结构中的所有对象时候 可以使用组合模式
//组合中的对象声明接口 在适当的情况下 实现所有类共有接口的默认行为//声明一个接口用户访问和管理component的子部件public abstract class Component{    protected String name;    public Component(String name){        this.name=name;    }    public abstract void add(Component c);    public abstract void remove(Component c);    public abstract void display(int depth);}//定义支节点行为 可以存储支节点或者叶节点public class Composite extends Component{    private List<Component> children = new ArrayList<Component>();    public Composite(String name){        super(name);    }    public void add(Component c){        children.add(c);    }    public void remove(Component c){        children.remove(c);    }    public void display(int depth){        StringBuilder sb = new StringBuilder();        for(int i=0;i<depth;i++){            sb.append("-");        }        System.out.println();        Iterator<Component> iterator = children.iterator();        while(iterator.hasNext()){            ((Component)(iterator.next())).display(depth+2);                    }       }}//定义叶节点行为 不能添加子节点public class Leaf extends Component{    public Leaf(String name){        super(name);    }    public void add(Component c){        System.out.println("Can not add to leaf");    }    public void remove(Component c){        System.out.println("Can not remove leaf");    }    public void display(int depth){        StringBuilder sb = new StringBuilder();        for(int i=0;i<depth;i++){            sb.append("-");                 }        System.out.println(sb.toString()+name);    }}
/** * 组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构。 * 组合模式使用得用户对单个对象和组合对象的使用具有一致性。 *  * 需求中体现部分与整体层次的结构时, * 以及希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,可以使用组合模式。 */public class TestComposite {    public static void main(String[] args) {        Composite root = new Composite("root");        root.add(new Leaf("Leaf A"));        root.add(new Leaf("Leaf B"));        Composite comp = new Composite("Composite X");        comp.add(new Leaf("Leaf XA"));        comp.add(new Leaf("Leaf XB"));        //comp.display(1);        root.add(comp);        Composite comp2 = new Composite("Composite XY");        comp2.add(new Leaf("Leaf XYA"));        comp2.add(new Leaf("Leaf XYB"));        comp.add(comp2);        root.add(new Leaf("Leaf C"));        Leaf leaf = new Leaf("Leaf D");        root.add(leaf);        root.remove(leaf);        //leaf.add(new Leaf("Leaf E"));        root.display(1);    }}
0 0
原创粉丝点击