《装饰器模式(极简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;
}
相关推荐
雾岛听蓝6 分钟前
Qt开发核心笔记:从HelloWorld到对象树内存管理与坐标体系详解
开发语言·经验分享·笔记·qt
無限進步D4 小时前
Java 运行原理
java·开发语言·入门
是苏浙4 小时前
JDK17新增特性
java·开发语言
阿里加多7 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood8 小时前
java中`==`和`.equals()`区别
java·开发语言·python
zs宝来了8 小时前
AQS详解
java·开发语言·jvm
telllong9 小时前
Python异步编程从入门到不懵:asyncio实战踩坑7连发
开发语言·python
And_Ii9 小时前
LCR 168. 丑数
c++
CoderMeijun10 小时前
C++ 时间处理与格式化输出:从 Linux 时间函数到 Timestamp 封装
c++·printf·stringstream·时间处理·clock_gettime
wjs202411 小时前
JavaScript 条件语句
开发语言