代理(Proxy)模式,狀態(State)模式都提供一個代理類。代碼與代理類打交道,而實際工作的類隱藏在代理類背后。當調用代理類中的一個函數時,代理類僅轉而去調用實現類中的相應的函數。這兩種模式是如此相似,從結構上看,可以認為代理模式只是狀態模式的一個特例。但是這兩個模式的內涵是不一樣的。
基本思想很簡單:代理類派生來自一個基類,由平行地派生來自同一個基類的一個或多個類提供實際的實現。當一個代理對象被創建的時候,一個實現對象就分配給了它,代理對象就將函數調用發給實現對象。
從結構上來看,代理模式和狀態模式的區別很簡單:代理模式只有一個實現類,而狀態模式有多個(一個以上)實現。認為這兩種設計模式的應用也不同:代理模式控制對其實現類的訪問,而狀態模式動態地改變其實現類。
(1)代理模式例子:
#include<iostream>
using namespace std;
class ProxyBase
{
public:
virtual void f()=0;
virtual void g()=0;
virtual void h()=0;
virtual ~ProxyBase(){}
};
class Implementation :public ProxyBase
{
public:
void f(){cout<<"Implementation.f()"<<endl;}
void g(){cout<<"Implementation.g()"<<endl;}
void h(){cout<<"Implementation.h()"<<endl;}
};
class Proxy: public ProxyBase
{
ProxyBase *implementation;
public:
Proxy(){implementation=new Implementation();}
~Proxy(){delete implementation;}
void f(){implementation->f();}
void g(){implementation->g();}
void h(){implementation->h();}
};
int main()
{
Proxy p;
p.f();
p.g();
p.h();
}
(2)狀態模式
#include<iostream>
using namespace std;
class Creature
{
class State
{
public:
virtual string response()=0;
};
class Frog : public State
{
public:
string response(){return "Ribbet!";}
};
class Prince:public State
{
public:
string response(){return "Darling!";}
};
State *state;
public:
Creature(): state(new Frog()){}
void greet()
{
cout<<state->response()<<endl;
}
void kiss()
{
delete state;
state=new Prince();
}
};
int main()
{
Creature creature;
creature.greet();
creature.kiss();
creature.greet();
}