0

0

复合图案

碧海醫心

碧海醫心

发布时间:2024-12-07 20:21:03

|

897人浏览过

|

来源于dev.to

转载

什么是复合模式?

复合模式是一种结构模式,允许您将对象组合成树结构来表示整体-部分层次结构。复合让客户可以统一处理单个对象和对象组合。

在复合模式中,有子元素的元素称为节点,没有子元素的元素称为叶子

什么时候使用它?

  • 当您需要整体、部分、父子或树状层次结构时,请使用复合模式。
  • 当你想让客户端统一对待树中的子节点和父节点时,请使用复合模式。

问题

我们正在尝试实现简单的文件系统。首先,我们需要文件和目录类。但随着我们的文件结构变得越来越大,客户端将很难持续检查每个对象是哪些类的实例。
文件系统是树状层次结构的完美示例,我们希望统一对待文件和目录。是时候使用复合模式了!

解决方案

复合图案

  1. 客户
    由于 filesystemcomponent,客户端不关心对象是文件还是目录的实例。此外,客户端不必编写 if 语句来确定他是否在正确的对象上调用正确的方法。

  2. 文件系统组件
    文件和目录被客户端视为文件系统组件。 filesystemcomponent 定义方法的默认行为,默认行为可以是异常、不执行任何操作、返回 null 或 false,任何对您的应用程序有意义的行为。

  3. 文件
    这是我们的叶子,重写打印方法,打印其名称和内容。

  4. 目录
    这是我们的节点,重写添加、删除、获取子节点的方法。 print 方法打印出它的名称并调用子组件的 print 方法,这样 client 就不需要调用每个组件的 print 方法。

结构

复合图案

MedPeer科研绘图
MedPeer科研绘图

生物医学领域的专业绘图解决方案,告别复杂绘图,专注科研创新

下载

java实现

public abstract class filesystemcomponent {

    protected string name;

    public filesystemcomponent(string name) {
        this.name = name;
    }

    public string getname() {
        return name;
    }

    public void print(int indentlevel) {
        throw new unsupportedoperationexception();
    }

    public void add(filesystemcomponent component) {
        throw new unsupportedoperationexception();
    }

    public void remove(int index) {
        throw new unsupportedoperationexception();
    }

    // instead of throwing exception, we do nothing by default.
    // doing nothing makes sense because leaf has no child.
    public void getchildren() {
    }
}
public class file extends filesystemcomponent {

    private string content;

    public file(string name, string content) {
        super(name);
        this.content = content;
    }

    @override
    public void print(int indentlevel) {
        string indent = " ".repeat(indentlevel);
        system.out.println(indent + name + ": " + content);
    }
}
public class directory extends filesystemcomponent {

    private list<filesystemcomponent> children;

    public directory(string name) {
        super(name);
        children = new arraylist<>();
    }

    @override
    public void print(int indentlevel) {
        string indent = " ".repeat(indentlevel);
        system.out.println(indent + name + " directory:");
        for (filesystemcomponent child : children) {
            child.print(indentlevel + 2);
        }
    }

    @override
    public void add(filesystemcomponent component) {
        children.add(component);
    }

    @override
    public void remove(int index) {
        children.remove(index);
    }

    @override
    public void getchildren() {
        if (children.isempty()) {
            return;
        }
        stringbuilder builder = new stringbuilder("[");
        for (filesystemcomponent child : children) {
            builder.append(child.getname() + ", ");
        }
        builder.delete(builder.length() - 2, builder.length());
        builder.append("]");
        system.out.println(builder);
    }
}
public class filesystemtestdrive {

    public static void main(string[] args) {
        filesystemcomponent rootdirectory = new directory("root");
        filesystemcomponent fruitsdirectory = new directory("fruits");
        filesystemcomponent animaldirectory = new directory("animal");
        filesystemcomponent felinedirectory = new directory("feline");

        rootdirectory.add(fruitsdirectory);
        rootdirectory.add(animaldirectory);

        fruitsdirectory.add(new file("appple", "red and juicy."));
        fruitsdirectory.add(new file("banana", "yellow and sweet."));
        fruitsdirectory.add(new file("lemon", "yellow and sour."));

        animaldirectory.add(felinedirectory);
        felinedirectory.add(new file("lion", "king of animal."));
        felinedirectory.add(new file("tiger", "has cool color pattern."));

        rootdirectory.print(0);
        rootdirectory.getchildren();
        rootdirectory.remove(0);
        rootdirectory.getchildren();

        // what happens we call getchildren() on leaf? (we don't override the method in leaf class)
        filesystemcomponent file = new file("sample", "this is leaf");
        file.getchildren(); // leaf calls default behavior, doing nothing
    }
}

输出:

Root directory:
  Fruits directory:
    Appple: red and juicy.
    Banana: yellow and sweet.
    Lemon: yellow and sour.
  Animal directory:
    Feline directory:
      Lion: King of animal.
      Tiger: Has cool color pattern.
[Fruits, Animal]
[Animal]

陷阱

  • 如果您想要一个组合使其子级保持特定顺序,则需要更复杂的管理方案来添加、删除和遍历子级。
  • 随着复合结构变得更大、更复杂,遍历的成本会更高。在这种情况下,您可能会考虑实现一个缓存来存储一些数据以节省遍历。

您可以在这里查看所有设计模式的实现。
github 存储库

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
python中print函数的用法
python中print函数的用法

python中print函数的语法是“print(value1, value2, ..., sep=' ', end=' ', file=sys.stdout, flush=False)”。本专题为大家提供print相关的文章、下载、课程内容,供大家免费下载体验。

192

2023.09.27

python print用法与作用
python print用法与作用

本专题整合了python print的用法、作用、函数功能相关内容,阅读专题下面的文章了解更多详细教程。

18

2026.02.03

c语言中null和NULL的区别
c语言中null和NULL的区别

c语言中null和NULL的区别是:null是C语言中的一个宏定义,通常用来表示一个空指针,可以用于初始化指针变量,或者在条件语句中判断指针是否为空;NULL是C语言中的一个预定义常量,通常用来表示一个空值,用于表示一个空的指针、空的指针数组或者空的结构体指针。

254

2023.09.22

java中null的用法
java中null的用法

在Java中,null表示一个引用类型的变量不指向任何对象。可以将null赋值给任何引用类型的变量,包括类、接口、数组、字符串等。想了解更多null的相关内容,可以阅读本专题下面的文章。

1089

2024.03.01

if什么意思
if什么意思

if的意思是“如果”的条件。它是一个用于引导条件语句的关键词,用于根据特定条件的真假情况来执行不同的代码块。本专题提供if什么意思的相关文章,供大家免费阅读。

846

2023.08.22

github中文官网入口 github中文版官网网页进入
github中文官网入口 github中文版官网网页进入

github中文官网入口https://docs.github.com/zh/get-started,GitHub 是一种基于云的平台,可在其中存储、共享并与他人一起编写代码。 通过将代码存储在GitHub 上的“存储库”中,你可以: “展示或共享”你的工作。 持续“跟踪和管理”对代码的更改。

4070

2026.01.21

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

22

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

48

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

93

2026.03.06

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Git 教程
Git 教程

共21课时 | 4.1万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.6万人学习

Git中文开发手册
Git中文开发手册

共0课时 | 94人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号