装饰器模式详解

8.9.6 装饰器模式

​ 装饰器模式是一种结构型模式,主要是给一个类添加更多功能;

示例代码:

c++ 复制代码
#include <iostream>
#include <string>

// 抽象基类:文本修饰器
class TextDecorator {
public:
    virtual std::string decorate(const std::string& text) const = 0;
};

// 具体修饰器:加粗修饰器
class BoldDecorator : public TextDecorator {
public:
    std::string decorate(const std::string& text) const override {
        return "<b>" + text + "</b>";
    }
};

// 具体修饰器:斜体修饰器
class ItalicDecorator : public TextDecorator {
public:
    std::string decorate(const std::string& text) const override {
        return "<i>" + text + "</i>";
    }
};

int main() {
    // 原始文本
    std::string text = "Hello, world!";

    // 创建修饰器对象
    TextDecorator* boldDecorator = new BoldDecorator();
    TextDecorator* italicDecorator = new ItalicDecorator();

    // 使用装饰器修饰文本
    std::string boldText = boldDecorator->decorate(text);
    std::string italicText = italicDecorator->decorate(text);

    // 显示修饰后的文本
    std::cout << "Bold Text: " << boldText << std::endl;
    std::cout << "Italic Text: " << italicText << std::endl;

    // 释放内存
    delete boldDecorator;
    delete italicDecorator;

    return 0;
}
相关推荐
位东风21 分钟前
【c++学习记录】状态模式,实现一个登陆功能
c++·学习·状态模式
hans汉斯23 分钟前
【人工智能与机器人研究】基于力传感器坐标系预标定的重力补偿算法
人工智能·算法·机器人·信号处理·深度神经网络
vortex52 小时前
算法设计与分析:分治、动态规划与贪心算法的异同与选择
算法·贪心算法·动态规划
前端拿破轮2 小时前
🤡🤡🤡面试官:就你这还每天刷leetcode?连四数相加和四数之和都分不清!
算法·leetcode·面试
雷羿 LexChien2 小时前
C++内存泄漏排查
开发语言·c++
地平线开发者3 小时前
征程 6|工具链量化简介与代码实操
算法·自动驾驶
嘉小华3 小时前
CMake 完全指南:第一章 - 构建的烦恼 - 为什么需要CMake?
c++
DoraBigHead3 小时前
🧠 小哆啦解题记——谁偷改了狗狗的台词?
算法
Kaltistss3 小时前
240.搜索二维矩阵Ⅱ
线性代数·算法·矩阵
Feliz Da Vida3 小时前
[代码学习] c++ 通过H矩阵快速生成图像对应的mask
c++·学习