《装饰器模式(极简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;
}
相关推荐
-VE-9 分钟前
myshell
linux·c++
沈韶珺42 分钟前
Visual Basic语言的云计算
开发语言·后端·golang
沈韶珺1 小时前
Perl语言的函数实现
开发语言·后端·golang
嘻嘻哈哈的zl1 小时前
初级数据结构:栈和队列
c语言·开发语言·数据结构
wjs20241 小时前
MySQL 插入数据指南
开发语言
美味小鱼1 小时前
Rust 所有权特性详解
开发语言·后端·rust
Bluesonli1 小时前
第 1 天:UE5 C++ 开发环境搭建,全流程指南
开发语言·c++·ue5·虚幻·unreal engine
wjs20242 小时前
三路排序算法
开发语言
憨猪在度假2 小时前
Cmake学习笔记
c++·笔记·学习
weixin_537590452 小时前
《C程序设计》第六章练习答案
c语言·c++·算法