《组合模式(极简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.
*/
}
相关推荐
AA陈超21 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P07-11 实现自动运行
c++·游戏·ue5·游戏引擎·虚幻
DARLING Zero two♡23 分钟前
【优选算法】LinkedList-Concatenate:链表的算法之契
数据结构·c++·算法·链表
yolo_guo29 分钟前
opencv 学习: 07 使用迭代器 (iterator) 遍历像素
linux·c++·opencv
yue00842 分钟前
C# 求取整数的阶乘
java·开发语言·c#
曹绍华1 小时前
android 线程loop
android·java·开发语言
树在风中摇曳1 小时前
C语言动态内存管理:从基础到进阶的完整解析
c语言·开发语言·算法
mjhcsp1 小时前
C++ 高精度计算:突破数据类型限制的实现与应用
开发语言·c++·算法·高精度
lixinnnn.1 小时前
C++: map和set
开发语言·c++
大袁同学1 小时前
【二叉搜索树】:程序的“决策树”,排序数据的基石
数据结构·c++·算法·决策树·stl
郝学胜-神的一滴2 小时前
Qt QPushButton 样式完全指南:从基础到高级实现
linux·开发语言·c++·qt·程序人生