设计模式学习—15组合模式

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_33334951/article/details/102664596

组合模式

UML

在这里插入图片描述

解释说明

  • 组合模式:将对象组合成树形结构以表示 ‘部分-整体’ 的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
  • 透明模式:Component中包含Add和Remove方法,这在Leaf中无意义。
  • 安全模式:Component中不包含Add和Remove方法,会增加调用节点时的判断。

代码实现

  • Component.class
package learn15;

public abstract class Component {
    protected String name;

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

    public abstract void add(Component c);

    public abstract void remove(Component c);

    public abstract void display(int depth);
}
  • Composite.class
package learn15;

import java.util.ArrayList;
import java.util.List;

public class Composite extends Component {

    private List<Component> children = new ArrayList<>();

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

    @Override
    public void add(Component c) {
        children.add(c);
    }

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

    @Override
    public void display(int depth) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            stringBuilder.append('-');
        }
        System.out.println(stringBuilder.toString() + name);

        for (Component c :
                children) {
            c.display(depth + 2);
        }
    }
}
  • Leaf.class
package learn15;

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

    @Override
    public void add(Component c) {
        System.out.println("叶子节点不能添加子节点!");
    }

    @Override
    public void remove(Component c) {
        System.out.println("叶子节点没有子节点!");
    }

    @Override
    public void display(int depth) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < depth; i++) {
            stringBuilder.append('-');
        }
        System.out.println(stringBuilder.toString() + name);
    }
}
  • Main.class
import learn15.*;

public class Main {

    public static void main(String[] args) throws Exception {
        Composite root = new Composite("root");
        root.add(new Leaf("Leaf A"));
        root.add(new Leaf("Leaf B"));

        Composite comp1 = new Composite("Composite X");
        comp1.add(new Leaf("Leaf C"));
        comp1.add(new Leaf("Leaf D"));
        root.add(comp1);

        Composite comp2 = new Composite("Composite Y");
        comp2.add(new Leaf("Leaf E"));
        comp2.add(new Leaf("Leaf F"));
        comp1.add(comp2);

        root.display(1);
    }
}

参考资料

  • 大话设计模式

猜你喜欢

转载自blog.csdn.net/qq_33334951/article/details/102664596
今日推荐