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

组合模式

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);
    }
}

参考资料

  • 大话设计模式
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值