设计模式之组合模式【Composite Pattern】

组合模式将一组相似的对象看作一个对象处理,并根据一个树状结构来组合对象,然后提供一个统一的方法去访问对象,以此忽略掉对象与对象集合之间的差别。
像文件和文件夹这种结构就是典型的组合模式。

1、定义

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

2、使用场景

  1. 表示对象的部分-整体层次结构时。
  2. 如果希望统一地使用组合结构中的所有对象。

3、UML图

4、示例代码

public abstract class Component {
    protected String name;

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

    public abstract void doSomething();

    public abstract void addChild(Component child);

    public abstract void removeChild(Component child);

    public abstract Component getChildren(int index);
}

//枝干节点
public class Composite extends Component {

    //存储所有子节点
    private List<Component> components = new ArrayList<Component>();

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

    @Override
    public void doSomething() {
        System.out.println(name + " doSomething");
        for(Component c : components) {
            c.doSomething();
        }
    }

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

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

    @Override
    public Component getChildren(int index) {
        return components.get(index);
    }
}

//叶子节点
public class Leaf extends Component {

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

    @Override
    public void doSomething() {
        System.out.println(name + " doSomething");
    }

    @Override
    public void addChild(Component child) {
        throw new UnsupportedOperationException("叶子节点不能添加子节点");
    }

    @Override
    public void removeChild(Component child) {
        throw new UnsupportedOperationException("叶子节点没有子节点");
    }

    @Override
    public Component getChildren(int index) {
        throw new UnsupportedOperationException("叶子节点没有子节点");
    }
}

客户端调用:

public class Client {

    public static void main(String[] args) {
        Component root = new Composite("根节点");
        Component branch1 = new Composite("节点1");
        Component leaf1 = new Composite("叶子节点1");
        Component leaf2 = new Composite("叶子节点2");
        Component leaf3 = new Composite("叶子节点3");

        root.addChild(branch1);
        root.addChild(leaf1);

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

        root.doSomething();
    }
}

调用结果:
这里写图片描述

5、安全性和透明性

像上述的实现方式,将组合所有使用的方法都定义在抽象类里的方式称为透明的组合模式。透明的组合模式中不管是叶子节点还是枝干节点都有着相同的结构。

与之对应的就是安全的组合模式,安全的组合模式就是将管理子节点的操作定义在 Composite 中。这种模式,客户端在使用的时候,就必须区分是枝干节点还是叶子节点。UML图如下:

猜你喜欢

转载自blog.csdn.net/iluojie/article/details/80385974