装饰器模式通过组合扩展对象功能,避免继承导致的类膨胀。定义Component接口,ConcreteComponent实现基础功能,Decorator继承Component并持有一个Component指针,LoggingDecorator在调用原对象前后添加日志行为,实现动态增强。

装饰器模式通过组合的方式动态扩展对象功能,避免使用继承带来的类爆炸问题。在C++中,可通过抽象基类和多层包装实现这一设计模式。
定义公共接口
所有被装饰对象和装饰器都需继承同一抽象接口,确保调用一致性。
class Component {
public:
virtual ~Component() = default;
virtual void operation() = 0;
};
实现具体组件
基础功能类实现接口,作为被装饰的原始对象。
class ConcreteComponent : public Component {
public:
void operation() override {
std::cout << "基础功能执行\n";
}
};
编写装饰器基类
装饰器继承自Component,并持有Component指针,形成包装结构。
立即学习“C++免费学习笔记(深入)”;
class Decorator : public Component {
protected:
Component* component;
public:
explicit Decorator(Component* c) : component(c) {}
virtual void operation() override {
component->operation();
}
};
添加具体装饰逻辑
子类重写operation,在调用原对象前后插入新行为。
class LoggingDecorator : public Decorator {
public:
using Decorator::Decorator;
void operation() override {
std::cout << "[日志] 开始执行操作\n";
Decorator::operation();
std::cout << "[日志] 操作完成\n";
}
};
class TimingDecorator : public Decorator {
public:
using Decorator::Decorator;
void operation() override {
auto start = std::chrono::high_resolution_clock::now();
Decorator::operation();
auto end = std::chrono::high_resolution_clock::now();
std::cout << "[性能] 耗时: "
<< std::chrono::duration_cast(end - start).count()
<< " 微秒\n";
}
};
组合使用多个装饰器
按需叠加装饰器,实现功能灵活组合。
int main() {
Component* comp = new ConcreteComponent();
comp = new LoggingDecorator(comp);
comp = new TimingDecorator(comp);
comp->operation();
// 注意:实际中应使用智能指针管理内存
delete comp;
return 0;
}
这种方式允许在运行时动态添加功能,比如网络请求前加认证、数据处理后加缓存。关键是保持接口统一,让外部无法感知是否被装饰。基本上就这些,不复杂但容易忽略细节。










