设计模式-组合

一,组合模式详解

  • 概念
    将对象以树形结构组织起来,以达成“部分-整体”的层次结构,使得客户端对单个对象和组合对象的使用具有一致性
    树的结构-->组合设计模式
  • 使用场景
    (1)需要表示一个对象整体或部分层次
    (2)让客户能忽略不同对象的层次变化
  • UML
    设计模式-组合_第1张图片
    image.png
  • 代码示例
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 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();
  • 优点
    (1)高层模块调用简单
    (2)节点自由增加

你可能感兴趣的:(设计模式-组合)