? ? ? ? 裝飾器模式是一種結構型設計模式,它允許在運行時擴展一個對象的功能,而不需要改變其現有結構。這種模式的核心思想是通過創建一個裝飾器來動態地增強或修改原有對象的行為。裝飾器模式是繼承的一個補充,提供了比繼承更加靈活的方式來擴展對象的行為。
一、編碼
? 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();