装饰器模式通过组合动态扩展对象功能,核心角色包括Component、ConcreteComponent、Decorator和ConcreteDecorator,以统一接口为基础,在不修改原类的前提下叠加行为,适用于文本样式、日志系统、数据流处理等场景,结合智能指针可提升内存安全性。

在C++中实现装饰器设计模式,核心是通过组合而非继承来动态扩展对象功能。它允许在运行时为某个对象添加新行为,同时不影响同类其他对象。这种模式特别适合需要灵活叠加功能的场景,比如图形界面控件、输入输出流处理等。
装饰器模式的基本结构
装饰器模式包含以下几个角色:
- Component(组件接口):定义对象的统一接口,可以是抽象类或纯虚类。
- ConcreteComponent(具体组件):实现基本功能的对象。
- Decorator(装饰器基类):持有Component指针,并实现相同接口,通常也继承自Component。
- ConcreteDecorator(具体装饰器):在调用原对象方法前后添加额外逻辑。
下面是一个简单示例,展示如何为一个文本显示功能逐步添加加粗、斜体等样式:
#include <iostream>
#include <string>
// 组件接口
class TextComponent {
public:
virtual ~TextComponent() = default;
virtual std::string display() const = 0;
};
// 具体组件:基础文本
class PlainText : public TextComponent {
std::string text;
public:
explicit PlainText(const std::string& t) : text(t) {}
std::string display() const override {
return text;
}
};
// 装饰器基类
class TextDecorator : public TextComponent {
protected:
TextComponent* component;
public:
explicit TextDecorator(TextComponent* c) : component(c) {}
virtual ~TextDecorator() { delete component; }
std::string display() const override {
return component->display();
}
};
// 具体装饰器:加粗
class BoldText : public TextDecorator {
public:
explicit BoldText(TextComponent* c) : TextDecorator(c) {}
std::string display() const override {
return "<b>" + TextDecorator::display() + "</b>";
}
};
// 具体装饰器:斜体
class ItalicText : public TextDecorator {
public:
explicit ItalicText(TextComponent* c) : TextDecorator(c) {}
std::string display() const override {
return "<i>" + TextDecorator::display() + "</i>";
}
};登录后复制
使用方式如下:
立即学习“C++免费学习笔记(深入)”;
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。
还木有评论哦,快来抢沙发吧~