代理(Proxy)模式,狀態(tài)(State)模式都提供一個(gè)代理類。代碼與代理類打交道,而實(shí)際工作的類隱藏在代理類背后。當(dāng)調(diào)用代理類中的一個(gè)函數(shù)時(shí),代理類僅轉(zhuǎn)而去調(diào)用實(shí)現(xiàn)類中的相應(yīng)的函數(shù)。這兩種模式是如此相似,從結(jié)構(gòu)上看,可以認(rèn)為代理模式只是狀態(tài)模式的一個(gè)特例。但是這兩個(gè)模式的內(nèi)涵是不一樣的。
基本思想很簡(jiǎn)單:代理類派生來自一個(gè)基類,由平行地派生來自同一個(gè)基類的一個(gè)或多個(gè)類提供實(shí)際的實(shí)現(xiàn)。當(dāng)一個(gè)代理對(duì)象被創(chuàng)建的時(shí)候,一個(gè)實(shí)現(xiàn)對(duì)象就分配給了它,代理對(duì)象就將函數(shù)調(diào)用發(fā)給實(shí)現(xiàn)對(duì)象。
從結(jié)構(gòu)上來看,代理模式和狀態(tài)模式的區(qū)別很簡(jiǎn)單:代理模式只有一個(gè)實(shí)現(xiàn)類,而狀態(tài)模式有多個(gè)(一個(gè)以上)實(shí)現(xiàn)。認(rèn)為這兩種設(shè)計(jì)模式的應(yīng)用也不同:代理模式控制對(duì)其實(shí)現(xiàn)類的訪問,而狀態(tài)模式動(dòng)態(tài)地改變其實(shí)現(xiàn)類。
(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)狀態(tài)模式
#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();
}