组合模式(Composite)

来源:互联网 发布:c语言程序头文件 编辑:程序博客网 时间:2024/05/22 07:47

组合模式:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

DEMO:

Component:

 * * @author A42J */public abstract class Component {    protected String name;    public void setName(String name) {        this.name = name;    }        public abstract void Add(Component c);    public abstract void Remove(Component c);    public abstract void Display(int depth);}

Composite:

//非叶子节点public class Composite extends Component {    //节点集合    private List<Component> children = new ArrayList<Component>();    public Composite(String name) {        super.setName(name);    }    @Override    public void Add(Component c) {        //添加子节点        children.add(c);    }    @Override    public void Remove(Component c) {        //删除子节点        children.remove(c);    }    @Override    public void Display(int depth)     {        //显示叶子节点        for(int i=0;i<children.size();i++)        {            Component c = children.get(i);            c.Display(depth+2);        }    }}

Leaf:

public class Leaf extends Component {    public Leaf(String Name) {        super.setName(Name);    }    @Override    //叶子节点没有子节点    public void Add(Component c) {        System.out.println("Cannot add to a Leaf");    }    @Override    //叶子节点不能删除子节点    public void Remove(Component c) {        System.out.println("Cannot remove to a Leaf");    }    @Override    //显示叶子节点(第几层)    public void Display(int depth) {        System.out.println("-" + depth + name);    }}


ComponentMain:

public class ComponentMain {    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"));                root.Add(comp);                Composite comp2 =  new Composite("Composite X");        comp2.Add(new Leaf("Leaf XYA"));        comp2.Add(new Leaf("Leaf XYB"));        comp.Add(comp2);        //试图在叶子节点上添加子节点(报错)        Leaf l = new Leaf("L A");        l.Add(new Leaf("Leaf LA"));        l.Add(new Leaf("Leaf LB"));        root.Add(l);        //临时长出的叶子节点C,D        root.Add(new Leaf("Leaf C"));        Leaf leaf = new Leaf("Leaf D");        root.Add(leaf);        //D节点又被风吹走了        root.Remove(leaf);        //从第一个节点开始显示        root.Display(1);                    }}


组合模式使用场合:当你发现需求中是体现部分与整体层次的结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该使用组合模式