欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 设计模式-装饰器

设计模式-装饰器

2025/2/13 21:20:44 来源:https://blog.csdn.net/fengchengwu2012/article/details/140181949  浏览:    关键词:设计模式-装饰器

        装饰器模式是一种结构型设计模式,它允许在运行时扩展一个对象的功能,而不需要改变其现有结构。这种模式的核心思想是通过创建一个装饰器来动态地增强或修改原有对象的行为。装饰器模式是继承的一个补充,提供了比继承更加灵活的方式来扩展对象的行为。

一、编码

  1、头文件

#ifndef _DECORATE_H__
#define  _DECORATE_H__
#include <iostream>
using namespace  std;
/// 抽象被装饰者
// template<class T,class U>  class Decoratee {
//     public:
//         virtual  U  execOpt(T t) = 0 ;
// };// template<class T,class U> class DecorateImpl: public Decoratee {
//      public:
//          U  execOpt(T t);
// };/// 抽象被装饰者
class  Decoratee{public:int  value;virtual  void  decorateeOpt() = 0 ;
};/// 被装饰者的具体实现
class DecorateeImpl : public Decoratee{public: DecorateeImpl();void  decorateeOpt() override;
};/// 定义装饰器接口
class  Decorator : public Decoratee {protected:Decoratee* decoratee;public:/// @brief  装饰器增强方法virtual  void  decoratorOpt() = 0;
};/// 扩展装饰器A
class  DecoratorImplA : public Decorator {public:DecoratorImplA(Decoratee* decoratee);void  decorateeOpt() override;  void  decoratorOpt() override;
};/// 扩展装饰器B
class  DecoratorImplB : public Decorator {public:DecoratorImplB(Decoratee* decoratee);void  decorateeOpt() override;  void  decoratorOpt() override;
};#endif

 2、函数定义

#include "decorate.h"// template<class T,class U>
// U  DecorateImpl<T,U>::execOpt(T t) {
//     cout << "" << endl;
// }DecorateeImpl::DecorateeImpl(){this->value = 1;
}void  DecorateeImpl::decorateeOpt(){this->value = this->value + 2; cout << "DecorateeImpl  execOpt  value = " << this->value << endl;
}DecoratorImplA::DecoratorImplA(Decoratee* decoratee) {this->decoratee = decoratee ;
}void  DecoratorImplA::decorateeOpt(){if(this->decoratee== nullptr){return;}this->decoratee->decorateeOpt();this->decoratorOpt();
}void  DecoratorImplA::decoratorOpt(){this->decoratee->value =  this->decoratee->value * 5;cout << "DecoratorImplA  execOpt  value = " <<  this->decoratee->value << endl;
}DecoratorImplB::DecoratorImplB(Decoratee* decoratee) {this->decoratee = decoratee ;
}void  DecoratorImplB::decorateeOpt(){if(this->decoratee== nullptr){return;}this->decoratee->decorateeOpt();DecoratorImplB::decoratorOpt();
}void  DecoratorImplB::decoratorOpt(){this->decoratee->value =  this->decoratee->value * 10;cout << "DecoratorImplB  execOpt  value = " <<  this->decoratee->value << endl;
}

二、测试

Decoratee*  decoratee = new DecorateeImpl();
Decorator*  decoratorA = new DecoratorImplA(decoratee);
Decorator*  decoratorB = new DecoratorImplA(decoratee);
decoratorA->decorateeOpt();
decoratorB->decorateeOpt();

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com