设计模式-组合

2018-05-07  本文已影响0人  ZjyMac

一,组合模式详解

public abstract class Component {
    private String name;

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

    public abstract void doSomeThing();

    public abstract void addChild(Component component);

    public abstract void removeChild(Component component);

    public abstract Component getChild(int position);
}
public class Composite extends Component {
    private List<Component> mFileList;

    public Composite(String name) {
        super(name);
        mFileList = new ArrayList<>();
    }

    @Override
    public void doSomeThing() {
        if (null != mFileList) {
            for (Component c : mFileList) {
                c.doSomeThing();
            }
        }
    }

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

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

    @Override
    public Component getChild(int index) {
        return mFileList.get(index);
    }
}
public class Leaf extends Component {
    public Leaf(String name) {
        super(name);
    }

    @Override
    public void doSomeThing() {

    }

    @Override
    public void addChild(Component component) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void removeChild(Component component) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Component getChild(int position) {
        throw new UnsupportedOperationException();
    }

}

Composite root = new Composite("root");
        Composite branch1 = new Composite("branch1");
        Composite branch2 = new Composite("branch2");
        Composite branch3 = new Composite("branch3");

        Leaf leaf1 = new Leaf("leaf1");
        Leaf leaf2 = new Leaf("leaf2");
        Leaf leaf3 = new Leaf("leaf3");

        branch1.addChild(leaf1);
        branch3.addChild(leaf2);
        branch3.addChild(leaf3);

        root.addChild(branch1);
        root.addChild(branch2);
        root.addChild(branch3);

        root.doSomeThing();
上一篇下一篇

猜你喜欢

热点阅读