《组合模式(极简c++)》

本文章属于专栏- 概述 - 《设计模式(极简c++版)》-CSDN博客


本章简要说明组合模式。本文分为**++模式说明、本质思想、实践建议、代码示例++**四个部分。

模式说明

  • 方案:组合模式是一种结构型设计模式,用于将对象组合成树形结构以表示"部分-整体"的层次结构。它使得客户端能够统一地处理单个对象和组合对象。
  • 优点:
    • 简化客户端代码:客户端无需区分单个对象和组合对象,可统一处理。
    • 灵活性和可扩展性:能够轻松添加新的组件,不影响现有代码。
  • 缺点:
    • 对于简单的层次结构,可能会引入过多的一般化类和接口。
    • 可能限制特定操作:某些操作可能在叶节点和组合节点上没有意义,需要客户端进行判断。

本质思想:类A中有一个数组,数组里面都是A*(可以实际指向A的派生类),这样可以建一个全是A的树

实践建议:在运行时,需要构建一个全是相同基类的树,并要统一处理时使用

代码示例:

cpp 复制代码
#include <iostream>
#include <vector>

class Bird {
public:
    Bird(int age):age_(age) {}

    void print() {
        std::cout << "Bird is " << age_ << " years old." << std::endl;
        for (auto& bird : birds) {
            bird->print();
        }
    }

    void add_son(Bird* bird) {
        birds.emplace_back(bird);
    }

private:
    int age_;
    std::vector<Bird*> birds;
};

class BirdSon : public Bird {
public:
    BirdSon(int age):Bird(age) {}
// ...Other interface
};

int main() {
    Bird* bird_father = new Bird(10);
    BirdSon* bird_big_son = new BirdSon(2);
    BirdSon* bird_litte_son = new BirdSon(1);
    bird_father->add_son(bird_big_son);
    bird_father->add_son(bird_litte_son);
    bird_father->print();
    delete bird_father;
    delete bird_big_son;
    delete bird_litte_son;
/*
输出:
    Bird is 10 years old.
    Bird is 2 years old.
    Bird is 1 years old.
*/
}
相关推荐
加油吧zkf几秒前
AI大模型如何重塑软件开发流程?——结合目标检测的深度实践与代码示例
开发语言·图像处理·人工智能·python·yolo
tan77º5 分钟前
【Linux网络编程】Socket - UDP
linux·服务器·网络·c++·udp
ejinxian16 分钟前
PHP 超文本预处理器 发布 8.5 版本
开发语言·php
GiraKoo37 分钟前
【GiraKoo】C++14的新特性
c++
软件黑马王子42 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon43 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
悠悠小茉莉1 小时前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
Da_秀1 小时前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
坏柠1 小时前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt