组合模式

本文介绍了一种软件设计模式——组合模式,该模式通过树形结构表示部分-整体的关系,使得用户可以一致地处理单个对象和复合对象。文章详细阐述了组合模式的组成部分,包括Component、Composite和Leaf,并给出了具体的实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

这里写图片描述

componsent抽象构建角色:定义共有的方法和属性
Leaf叶子对象:其下没有分支,是最小的遍历结构
Composite树枝对象:组合树枝节点和叶子节点形成一个树形结构

abstract class Component{
    public void doSomeThing() {/
    }
}

//树枝类
class Composite extends Component {
    //组合模式最重要的就是这个数组,存储一层中所有的树枝,树叶
    private ArrayList<Component> componentList = new ArrayList<>();

    public void add(Component component) {
        this.componentList.add(component);
    }

    public void remove(Component component) {
        this.componentList.remove(component);
    }

    public ArrayList<Component> getComponent() {
        return this.componentList;
    }
}

//叶子类
class Leaf extends Component{
    @Override
    public void doSomeThing() {
        super.doSomeThing();

    }
}

public class Test {
    public static void main(String[] args){
        Composite root = new Composite();

        Composite branch = new Composite();
        root.add(branch);

        Leaf leaf = new Leaf();
        branch.add(leaf);

        show(root);
    }

    public static void show(Composite composite) {
        for (Component c: composite.getComponent()) {
            if(c instanceof Leaf)
                c.doSomeThing();
            else
                show((Composite)c);
        }
    }
}
优点:

1、高层模块调用简单:树枝、树叶有公共的父类,高层模块不需要区分树枝、树叶类。
2、节点自由增加

缺点:

树枝、树叶直接继承Component类,与依赖倒置相违背

应用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值