设计模式--组合模式

Java工程源码

类图

这里写图片描述


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


优点
- 高层模块调用简单 高层模块不必关心自己处理的是单个对象还是整个组合结构
- 节点自由增加

缺点
- 场景类中,树枝和树叶使用时都需用起实现类,与依赖倒置原则冲突,没有面向接口编程


使用场景
- 维护和展示部分 - 整体关系的场景,如树形菜单,文件和文件夹管理
- 从一个整体中能够独立出部分模块或功能的场景

只要是树形结构就可以考虑使用组合模式


抽象构件

public abstract class Component {
    /**
     * 个体和整体都具有的共享
     */
    public abstract void operation();
}

树枝构件

public class Composite extends Component {
    private ArrayList<Component> componentArrayList = new ArrayList<>();

    public void add(Component param) {
        this.componentArrayList.add(param);
    }

    public void remove(Component param) {
        this.componentArrayList.remove(param);
    }

    public ArrayList<Component> getChild() {
        return this.componentArrayList;
    }

    @Override
    public void operation() {
        System.out.println("Composite->operation()");
    }
}

树叶构件

public class Leaf extends Component {
    private String name;

    public Leaf(String name) {
        System.out.println("新建树叶:" + name);
        this.name = name;
    }

    @Override
    public void operation() {
        System.out.println("Leaf->" + name);
    }
}

场景类

public class Client {
    public static void main(String[] args) {
        // 创建一个根节点
        Composite root = new Composite();
        root.operation();
        /*
                  root
                  /  \
             branch   leaf3
             /   \
          leaf1   leaf2
         */
        Composite branch = new Composite();
        branch.add(new Leaf("leaf1"));
        branch.add(new Leaf("leaf2"));

        root.add(branch);
        root.add(new Leaf("leaf3"));

        display(root);
    }

    public static void display(Composite root) {
        for (Component c : root.getChild()) {
            if (c instanceof Leaf) {
                c.operation();
            } else {
                display((Composite) c);
            }
        }
    }
}

运行结果

Composite->operation()
新建树叶:leaf1
新建树叶:leaf2
新建树叶:leaf3
Leaf->leaf1
Leaf->leaf2
Leaf->leaf3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值