设计模式之Composite模式(笔记)

组合模式:将对象组合成树形结构以表示“部分-总体”的层次结构。

组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用场合:当需求中是体现部分与总体层次的结构时,以及希望用户能够忽略组合对象与单个对象的不同,统一地使用组合结构中的全部对象时,就应该考虑用组合模式。


这里写图片描写叙述
首先定义一个Componet抽象类

public abstract class Component {
    protected String name;

    public Component(String name){
        this.name=name;
    }
    //抽象方法
    public abstract void add(Component c);
    public abstract void delete(Component c);
    public abstract void dispaly(int depth);
}

定义叶结点对象Leaf,继承Componet

public class Leaf extends Component {

    public Leaf(String name) {
        super(name);

    }

    @Override
    public void add(Component c) {
        System.out.println("can not add a leaf");

    }

    @Override
    public void delete(Component c) {
        System.out.println("can not delete a leaf");

    }

    @Override
    public void dispaly(int depth) {
        char[] ch=new char[depth];
        for(int i=0;i<depth;i++){
            ch[i]='-';
        }
        System.out.println(new String(ch)+name);        
    }
}

结点定义枝结点Composite继承Component

public class Composite extends Component{

    private List<Component> children=new ArrayList<Component>();
    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component c) {

        children.add(c);
    }

    @Override
    public void delete(Component c) {
        children.remove(c);

    }

    @Override
    public void dispaly(int depth) {
        char[] ch=new char[depth];
        for(int i=0;i<depth;i++){
            ch[i]='-';
        }
        System.out.println(new String(ch)+name);
        Iterator<Component> iterator=children.iterator();
        while(iterator.hasNext()){
            Component component=iterator.next();
            component.dispaly(depth+2);
        }
    }
   }

client代码


       public static void main(String[] args) {
         //组合模式
        Composite root=new Composite("root");
        root.add(new Leaf("LeafA"));
        root.add(new Leaf("LeafB"));
        Composite comp=new Composite("Composite X");
        comp.add(new Leaf("LeafXA"));
        comp.add(new Leaf("LeafXB"));
        root.add(comp);

        Composite comp2=new Composite("Composite Y");
        comp2.add(new Leaf("LeafXYA"));
        comp2.add(new Leaf("LeafXYB"));
        root.add(comp2);

        root.add(new Leaf("LeafC"));

        root.dispaly(1);
}

结果:
-root
- - -LeafA
- - -LeafB
- - -Composite X
- - - - -LeafXA
- - - - -LeafXB
- - -Composite Y
- - - - -LeafXYA
- - - - -LeafXYB
- - -LeafC

原文地址:https://www.cnblogs.com/lcchuguo/p/5342211.html