当前位置: 首页 > news >正文

【玩转23种Java设计模式】结构型模式篇:组合模式

软件设计模式(Design pattern),又称设计模式,是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。

汇总目录链接:【玩转23种Java设计模式】学习目录汇总整理

文章目录

  • 一、简介
  • 二、实例
    • 1、抽象组件
    • 2、叶子节点:文件
    • 3、组合节点:文件夹
    • 4、客户端使用
  • 三、总结
    • 1、优点
    • 2、缺点
    • 3、应用场景

一、简介

  组合模式(Composite Pattern)是一种结构型设计模式,用于将对象组合成树形结构以表示"部分-整体"的层次关系。其核心思想是通过统一接口处理叶子对象(单个元素)和组合对象(容器元素),使客户端无需区分操作的是单个对象还是整个组合结构。

核心角色:

  • Component:声明组合对象的通用接口
  • Leaf:叶子节点(无子节点)
  • Composite:容器节点(包含子组件集合)

二、实例

假设需要构建文件系统,包含文件夹(组合对象)和文件(叶子对象)。

1、抽象组件

interface FileSystemComponent {
    void display(int indent);
    long getSize();
}

2、叶子节点:文件

class File implements FileSystemComponent {
    private String name;
    private long size;

    public File(String name, long size) {
        this.name = name;
        this.size = size;
    }

    @Override
    public void display(int indent) {
        System.out.println(" ".repeat(indent) + "📄 " + name + " (" + size + "KB)");
    }

    @Override
    public long getSize() { return size; }
}

3、组合节点:文件夹

class Directory implements FileSystemComponent {
    private String name;
    private List<FileSystemComponent> children = new ArrayList<>();

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

    public void add(FileSystemComponent component) {
        children.add(component);
    }

    @Override
    public void display(int indent) {
        System.out.println(" ".repeat(indent) + "📁 " + name);
        children.forEach(child -> child.display(indent + 2));
    }

    @Override
    public long getSize() {
        return children.stream().mapToLong(FileSystemComponent::getSize).sum();
    }
}

4、客户端使用

public class Demo {
    public static void main(String[] args) {
        Directory root = new Directory("Root");
        
        Directory documents = new Directory("Documents");
        documents.add(new File("resume.pdf", 256));
        documents.add(new File("notes.txt", 128));
        
        Directory images = new Directory("Images");
        images.add(new File("photo1.jpg", 2048));
        
        root.add(documents);
        root.add(images);
        
        root.display(0);
        System.out.println("Total size: " + root.getSize() + "KB");
    }
}

输出示例:
📁 Root
📁 Documents
📄 resume.pdf (256KB)
📄 notes.txt (128KB)
📁 Images
📄 photo1.jpg (2048KB)
Total size: 2432KB

三、总结

1、优点

  • 简化客户端代码:统一处理单个对象与组合结构。
  • 高扩展性:新增组件类型无需修改现有代码。
  • 天然支持递归结构:方便实现树形操作(如遍历、统计)。

2、缺点

  • 类型安全性问题:需要运行时类型检查。
  • 接口设计难度:需兼顾叶子与容器的不同需求。
  • 可能违反接口隔离原则:需要为不需要的方法提供空实现。

3、应用场景

  • GUI组件库(窗口包含面板/按钮等)。
  • 组织架构管理系统(部门包含员工/子部门)。
  • 数学表达式解析(操作符包含子表达式)。
  • 游戏场景图(父节点包含子节点)。
  • XML/JSON文档处理。

  当系统需要处理树形结构,且希望以统一方式操作层次中的不同元素时,组合模式是最佳选择。其价值在于模糊了简单元素与复杂元素的边界,让复杂的层次结构变得易于管理和扩展。


文章转载自:

http://oZrcTIoy.rLdph.cn
http://KWQq5huH.rLdph.cn
http://2IUgRR8U.rLdph.cn
http://Os4G8sOH.rLdph.cn
http://EtmGWdU3.rLdph.cn
http://CUe7vanJ.rLdph.cn
http://Noln3UKu.rLdph.cn
http://yty6aK7n.rLdph.cn
http://1zVfdHsr.rLdph.cn
http://QR4LTHBC.rLdph.cn
http://CcLlUcGq.rLdph.cn
http://t73Usv6t.rLdph.cn
http://mysPYH4y.rLdph.cn
http://BBqLIxDQ.rLdph.cn
http://goEvdqHm.rLdph.cn
http://zReikY9y.rLdph.cn
http://GZqqRqCV.rLdph.cn
http://EWMXGiJI.rLdph.cn
http://5kXMCrKJ.rLdph.cn
http://w616qvdi.rLdph.cn
http://u8HCLcuX.rLdph.cn
http://DxPAUXdJ.rLdph.cn
http://t6wRyJBU.rLdph.cn
http://qU92uYWW.rLdph.cn
http://j3N7zk33.rLdph.cn
http://LTxUIkeV.rLdph.cn
http://voEuSpxG.rLdph.cn
http://cUJLeX68.rLdph.cn
http://G5F9uvSf.rLdph.cn
http://rGY3goZY.rLdph.cn
http://www.dtcms.com/a/57620.html

相关文章:

  • (最新教程)Cursor Pro订阅升级开通教程,使用支付宝订阅Cursor Pro Plus
  • saltstack通过master下发脚本批量修改minion_id,修改为IP
  • Spring使用@Scheduled注解的参数详解
  • 【数据仓库与数据挖掘基础】决策分析
  • ChromeDriver下载 最新版本 134.0.6998.35
  • WebUSB的常用API及案例
  • 【Python 数据结构 10.二叉树】
  • 爬虫案例七Python协程爬取视频
  • c++ auto关键字
  • SQL经典查询
  • 基于DeepSeek实现PDF嵌入SVG图片无损放大
  • CarPlanner:用于自动驾驶大规模强化学习的一致性自回归轨迹规划
  • 修改jupyter notebook的工作空间
  • HCIA复习拓扑实验
  • 兴业银行的笔试题及答案(2025)
  • 数据安全防线:备份文件的重要性与自动化实践
  • 计算机组成原理:数据表示的基本概念
  • 如何在Ubuntu上直接编译Apache Doris
  • mysql虚拟列
  • 基于SpringBoot的商城管理系统(源码+部署教程)
  • .Net 6 上传文件接口 文件大小报错整体配置
  • ARMv8寄存器的介绍
  • 【十三】Golang 通道
  • 机器始终是一个机器:技术本质与哲学边界
  • l c a
  • 数据安全基石:备份文件的重要性与自动化实践
  • Elasticsearch:使用 BigQuery 提取数据
  • C语言-文件操作 文件的随机读写
  • Ubuntu 下 nginx-1.24.0 源码分析 - cycle->modules[i]->type
  • P8662 [蓝桥杯 2018 省 AB] 全球变暖--DFS