《组合模式(极简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.
*/
}
相关推荐
BUG研究员_几秒前
Runnable与LCEL
开发语言·人工智能·python
果果燕1 小时前
实习笔记(一):NFS、Samba、VNC、Git、CMake、systemd、内核、交叉编译
linux·arm开发·c++·笔记·git
牛艺翔2 小时前
C++基础
开发语言·c++
键盘会跳舞2 小时前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
美味蛋炒饭.2 小时前
Git 版本控制(下)
开发语言·git·学习·总结·后端开发
我星期八休息2 小时前
网络编程—网络层
开发语言·前端·网络·人工智能·智能路由器
不负岁月无痕3 小时前
简单理解操作系统结构
java·linux·c语言·开发语言·c++·面试
余额瞒着我当琳3 小时前
C++模板初阶与STL初探
android·java·c++
SomeB1oody3 小时前
【RustyML入门】2.9. MeanShift
开发语言·后端·机器学习·rust·教程
萧瑟其中~3 小时前
多线程锁详解:互斥锁·自旋锁·读写锁(CAS + futex 原理)
开发语言·c++