组合模式——对象结构型模式

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

  • 你想表示对象的部分-整体层次结构
  • 你希望用户忽略组合对象与单个对象的不同,用户将统一使用组合结构中的所有对象。

三、结构
这里写图片描述

四、代码

public  abstract class Component {
    protected String name; //节点名
    public Component(String name){
        this.name = name;
    }

    public abstract void doSomething();
}
public class Composite extends Component {
    /**
     * 存储节点的容器
     */
    private List<Component> components = new ArrayList<>();

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

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

        if(null!=components){
            for(Component c: components){
                c.doSomething();
            }
        }
    }

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

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

    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);
    }
}
public class Client {
    public static void main(String[] args){
        // 构造一个根节点
        Composite root = new Composite("Root");

        // 构造两个枝干节点
        Composite branch1 = new Composite("Branch1");
        Composite branch2 = new Composite("Branch2");

        // 构造两个叶子节点
        Leaf leaf1 = new Leaf("Leaf1");
        Leaf leaf2 = new Leaf("Leaf2");

        branch1.addChild(leaf1);
        branch2.addChild(leaf2);

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

        root.doSomething();
    }
}

输出结果:
Root
Branch1
Leaf1
Branch2
Leaf2
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值