
装饰器模式通过组合的方式动态扩展对象功能,避免使用继承带来的类爆炸问题。在C++中,可通过抽象基类和多层包装实现这一设计模式。
定义公共接口所有被装饰对象和装饰器都需继承同一抽象接口,确保调用一致性。
class Component {
public:
virtual ~Component() = default;
virtual void operation() = 0;
};
实现具体组件
基础功能类实现接口,作为被装饰的原始对象。
class ConcreteComponent : public Component {
public:
void operation() override {
std::cout << "基础功能执行\n";
}
};
编写装饰器基类
装饰器继承自Component,并持有Component指针,形成包装结构。
PIA
全面的AI聚合平台,一站式访问所有顶级AI模型
226
查看详情
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";
}
};
<p>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<std::chrono::microseconds>(end - start).count()
<< " 微秒\n";
}
};</p> 组合使用多个装饰器
按需叠加装饰器,实现功能灵活组合。
int main() {
Component* comp = new ConcreteComponent();
comp = new LoggingDecorator(comp);
comp = new TimingDecorator(comp);
comp->operation();
<pre class='brush:php;toolbar:false;'>// 注意:实际中应使用智能指针管理内存
delete comp;
return 0; }
这种方式允许在运行时动态添加功能,比如网络请求前加认证、数据处理后加缓存。关键是保持接口统一,让外部无法感知是否被装饰。基本上就这些,不复杂但容易忽略细节。
以上就是C++如何实现装饰器模式在类中扩展功能的详细内容,更多请关注知识资源分享宝库其它相关文章!
相关标签: c++ 子类 指针 继承 接口 对象 大家都在看: C++0x兼容C吗? C/C++标记? c和c++学哪个 c语言和c++先学哪个好 c++中可以用c语言吗 c++兼容c语言的实现方法 struct在c和c++中的区别






发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。