装饰器模式详解

小明 2025-04-30 13:54:11 8
8.9.6 装饰器模式

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

()

示例代码:

#include 
#include 
// 抽象基类:文本修饰器
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 "" + text + "";
    }
};
// 具体修饰器:斜体修饰器
class ItalicDecorator : public TextDecorator {
public:
    std::string decorate(const std::string& text) const override {
        return "" + text + "";
    }
};
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 
The End
微信