定义
装饰器模式(Decorator Pattern)是一种结构型设计模式。
装饰器模式通过创建一个装饰类,包装原始对象,并在保持原始对象接口不变的情况下,扩展其功能。
模式示例
#include <iostream>
#include <string>// 基础文本输出类
class TextOutput {
public:virtual void write(const std::string& text) {std::cout << text;}
};// 装饰器基类
class TextDecorator : public TextOutput {
protected:TextOutput* textOutput;
public:TextDecorator(TextOutput* output) : textOutput(output) {}void write(const std::string& text) override {textOutput->write(text);}
};// 具体的装饰器类:粗体
class BoldDecorator : public TextDecorator {
public:BoldDecorator(TextOutput* output) : TextDecorator(output) {}void write(const std::string& text) override {std::cout << "<b>" << text << "</b>";}
};// 具体的装饰器类:斜体
class ItalicDecorator : public TextDecorator {
public:ItalicDecorator(TextOutput* output) : TextDecorator(output) {}void write(const std::string& text) override {std::cout << "<i>" << text << "</i>";}
};int main() {// 创建基础文本输出对象TextOutput* textOutput = new TextOutput();// 创建装饰器并嵌套组合TextDecorator* boldDecorator = new BoldDecorator(textOutput);TextDecorator* italicDecorator = new ItalicDecorator(boldDecorator);// 输出文本italicDecorator->write("Hello, World!");// 释放内存delete italicDecorator;delete boldDecorator;delete textOutput;return 0;
}