《装饰器模式(极简c++)》

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


模式说明:

  • 方案: 装饰类和派生类同根,然后装饰类中放一个派生类,以在接口不动的情况下增加功能
  • 优点: 可以灵活地扩展对象功能,相比继承更易读。
  • 缺点: 增加了许多小对象,易于出错,不易调试。

本质思想: 派生类和装饰类都继承Base,然后装饰器类中放一个Base指针,存派生类。这样装饰器类和派生类可以放一个数组中,调用相同接口,这样部分类的功能看起来像被装饰了。前面是核心思想,基于这个再扩展,很容易基于装饰器加装饰器,或者把有相似接口的装饰器抽象出一个装饰器基类。

实践建议:

  • 注意组合关系,确保装饰器和被装饰对象之间的接口一致。
  • 装饰器的功能应该是可组合的,可叠加的。

代码示例:

cpp 复制代码
#include <iostream>

// Component Interface
class Bird {
public:
    virtual void fly() const = 0;
};

// Concrete Component
class Sparrow : public Bird {
public:
    void fly() const override {
        std::cout << "Sparrow is flying." << std::endl;
    }
};

// Concrete Decorator
class RedFeatherDecorator : public Bird {
private:
    Bird *bird;

public:
    explicit RedFeatherDecorator(Bird *b) : bird(b) {}

    void fly() const override {
        bird->fly();
        std::cout << "With red feathers." << std::endl;
    }
};

int main() {
    Bird *sparrow = new Sparrow();
    Bird *redSparrow = new RedFeatherDecorator(sparrow);

    redSparrow->fly();

/* 
输出:
    Sparrow is flying.
    With red feathers.
*/
    delete sparrow;
    delete redSparrow;

    return 0;
}
相关推荐
t***5448 小时前
Clang 编译器在 Orwell Dev-C++ 中的局限性
开发语言·c++
oy_mail9 小时前
QoS质量配置
开发语言·智能路由器·php
oyzz1209 小时前
PHP操作redis
开发语言·redis·php
nashane9 小时前
HarmonyOS 6学习:网络能力变化监听与智能提示——告别流量偷跑,打造贴心网络感知应用
开发语言·php·harmony app
yolo_guo10 小时前
redis++使用: hmset 与 hmget
c++·redis
凌波粒10 小时前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
handler0110 小时前
拒绝权限报错!三分钟掌握 Linux 权限管理
linux·c语言·c++·笔记·学习
拾贰_C10 小时前
【Google | Gemini | API | POST】怎么使用Google 的Gemini API (原生版)
开发语言·lua
t***54411 小时前
如何在Dev-C++中选择Clang编译器
开发语言·c++