<pre name="code" class="cpp">
<span style="font-size:18px;">// test01.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
#include<string>
#include<stdio.h>
using namespace std;
//抽象基類,定義一個對象接口,可以爲這個接口動態的添加職責
class Component
{
public:
Component() {}
virtual ~Component() {}
//純虛函數,由派生類實現
virtual void Operation() = 0;
};
//派生自Component,在這裏表示需要給它動態添加職責的類
class ConcreteComponent :public Component
{
public:
ConcreteComponent() {};
~ConcreteComponent() {};
void Operation()
{
cout << "ConcreteComponent operator.." << endl;
}
};
//抽象基類,維護一個指向Component對象的指針
class Decorator :public Component
{
public:
Decorator(Component *com)
{
this->_com = com;
}
void Operation() { };
virtual ~Decorator()
{
//delete _com;
}
protected:
Component *_com;
};
//派生自Decorator,用來裝飾ConcreteComponent類(這裏ConcreteComponent類只是基類Component派生出的一個類,也可以是其他類)
class ConcreteDecoratorA :public Decorator
{
public:
ConcreteDecoratorA(Component *com) :Decorator(com) {};
virtual void Operation()
{
_com->Operation();
AddedBehaviorA();
}
void AddedBehaviorA()
{
cout << "ConcreteDecoratorA::AddedBehaviorA..." << endl;
}
virtual ~ConcreteDecoratorA() {}
};
//也是派生自Decorator,用來裝飾ConcreteComponent類
class ConcreteDecoratorB:public Decorator
{
public:
ConcreteDecoratorB(Component *com) :Decorator(com) {};
virtual void Operation()
{
_com->Operation();
AddedBehaviorB();
}
void AddedBehaviorB()
{
cout << "ConcreteDecoratorB::AddedBehaviorB..." << endl;
}
virtual ~ConcreteDecoratorB() {}
};
int main()
{
//初始化一個ConcreteComponent對象
ConcreteComponent *com = new ConcreteComponent();
//採用這個ConcreteComponent對象去初始化一個ConcreteDecoratorA對象
//這樣就可以爲這個Component對象動態添加職責
ConcreteDecoratorA *decA = new ConcreteDecoratorA(com);//裝飾A
ConcreteDecoratorB *decB = new ConcreteDecoratorB(decA);//裝飾B
decB->Operation();
delete com;
delete decA;
delete decB;
return 0;
} </span>
裝飾模式的關鍵點:在Decorator裏面定義了一個Compontent 定義了一個指向Component的指針,從而可以實現多態,動態綁定各個派生類。
PS.如果只有一個ConcreteComponent類,就可以不需要Component這個抽象類,這樣直接讓Decorator類繼承ConcreteComponent類就可以了。同樣的道理,如果只有一個ConcreteDecorator類,那麼就沒有必要建立一個單獨Decorator類,而可以把Decorator類和ConcreteDecorator類的責任合併成一個類。