《组合模式(极简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.
*/
}
相关推荐
huohaiyu13 分钟前
Hashtable,HashMap,ConcurrentHashMap之间的区别
java·开发语言·多线程·哈希
Predestination王瀞潞4 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力6 小时前
C++继承
开发语言·c++
沿着路走到底7 小时前
python 基础
开发语言·python
沐知全栈开发8 小时前
C# 委托(Delegate)
开发语言
江公望8 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt
任子菲阳8 小时前
学Java第三十四天-----抽象类和抽象方法
java·开发语言
csbysj20209 小时前
如何使用 XML Schema
开发语言
R6bandito_9 小时前
STM32中printf的重定向详解
开发语言·经验分享·stm32·单片机·嵌入式硬件·mcu
逆小舟9 小时前
【C/C++】指针
c语言·c++·笔记·学习