行业知识
装饰器模式详解
2026-11-08 08:32:43
来源:互联网转载
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
上一篇:英文单词失望怎么写?