建站如何掙錢seo教程網(wǎng)站優(yōu)化
目錄
C++設(shè)計(jì)模式-裝飾器(Decorator)
一、意圖
二、適用性
三、結(jié)構(gòu)
四、參與者
五、代碼
C++設(shè)計(jì)模式-裝飾器(Decorator)
一、意圖
動(dòng)態(tài)地給一個(gè)對象添加一些額外的職責(zé)。就增加功能來說,Decorator模式相比生成子類更為靈活。
二、適用性
- 在不影響其他對象的情況下,以動(dòng)態(tài)、透明的方式給單個(gè)對象添加職責(zé)。
- 處理那些可以撤消的職責(zé)。
- 當(dāng)不能采用生成子類的方法進(jìn)行擴(kuò)充時(shí)。一種情況是,可能有大量獨(dú)立的擴(kuò)展,為支持每一種組合將產(chǎn)生大量的子類,使得子類數(shù)目呈爆炸性增長。另一種情況可能是因?yàn)轭惗x被隱藏,或類定義不能用于生成子類。
三、結(jié)構(gòu)
?
四、參與者
- Component
????????定義一個(gè)對象接口,可以給這些對象動(dòng)態(tài)地添加職責(zé)。
- ConcreteDecorator
???????定義一個(gè)對象,可以給這個(gè)對象添加一些職責(zé)。
- Decorator
????????維持一個(gè)指向Component對象的指針,并定義一個(gè)與Component接口一致的接口。
- ConcreteComponent
????????向組件添加職責(zé)。
五、代碼
#include<iostream>
using namespace std;class Component {
public:virtual void Operation() = 0;
};class ConcreteComponent : public Component{
public:virtual void Operation() {cout << "ConcreteComponent" << endl;}
};class Decorator : public Component {
public:Decorator(Component* tempComponent) :component(tempComponent) {}virtual void Operation() {component->Operation();}
private:Component* component;
};class ConcreteDecoratorA : public Decorator {
public:ConcreteDecoratorA(Component* tempComponent) :Decorator(tempComponent) {}virtual void Operation() {Decorator::Operation();cout << "ConcreteDecoratorA" << endl;}
};class ConcreteDecoratorB : public Decorator {
public:ConcreteDecoratorB(Component* tempComponent) :Decorator(tempComponent) {}virtual void Operation() {Decorator::Operation();cout << "ConcreteDecoratorB" << endl;}
};int main() {Component* component = new ConcreteComponent;component->Operation();Component* componentA = new ConcreteDecoratorA(component);componentA->Operation();Component* componentB = new ConcreteDecoratorB(component);componentB->Operation();return 0;
}