《组合模式(极简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.
*/
}
相关推荐
驭渊的小故事1 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
南风84112 小时前
C++ 四种强制类型转换详解
c++
Sakura_j_h_2 小时前
MCP SDK 2.0 实战:用 MCPServer 搭本地笔记检索服务
开发语言·笔记·python·qt·ai工具·mcp·mcpserver
微笑星河q2 小时前
C++STL【vector】常用接口函数使用和迭代器失效问题
开发语言·c++
Eider19983 小时前
Python基础语法之并发相关3
开发语言·python
FRing033 小时前
vue2干货总结11(短信验证、登录功能、统一处理错误(响应拦截器)、将token信息存入vuex、vuex持久化处理)
开发语言·前端·javascript·vue.js·vue2
CS_Zero4 小时前
DeepSeek V4.1 Flash 1017 (Batch) 新手极速上手指南
开发语言·batch·deepseek
山楂树の4 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
Risehuxyc4 小时前
C# 发展历史
开发语言·c#
HaiXCoder5 小时前
C++ 表达式怎么读:从一行代码到类型、值类别和生命周期
c++