设计模式之组合模式

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

 

public abstract class Component {
    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void add(Component component);

    public abstract void remove(Component component);

    public abstract void show(int stamp);

}

 

public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        throw new UnsupportedOperationException("不支持该操作。");
    }

    @Override
    public void remove(Component component) {
        throw new UnsupportedOperationException("不支持该操作。");
    }

    @Override
    public void show(int stamp) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < stamp; i++) {
            builder.append("-");
        }
        System.out.println(builder + name);
    }
}

 

public class Composite extends Component {
    private List<Component> child = new ArrayList<>();

    public Composite(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {
        child.add(component);
    }

    @Override
    public void remove(Component component) {
        child.remove(component);
    }

    @Override
    public void show(int stamp) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < stamp; i++) {
            builder.append("-");
        }
        System.out.println(builder + name);
        for (Component component : child) {
            component.show(stamp + 2);
        }
    }
}

 

public class CompositeDemo {
    public static void main(String[] args) {
        Composite root = new Composite("root");
        root.add(new Leaf("AA"));
        root.add(new Leaf("BB"));
        root.show(1);
    }
}

 

posted @ 2017-10-05 13:12  emoji的博客  阅读(151)  评论(0编辑  收藏  举报