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;
}