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