Proxy模式和State模式,都是提供一個Srurogate代理類,代碼只與代理類打交道,實際工作的類隱藏在代理類的后面。調用代理類中的一個方法時,僅僅是調用實現類中相應的方法。
基本思想:Surrogate代理類派生自一個基類,實現類和代理類一樣派生自相同的基類。
Proxy模式和State模式區別:結構上,Proxy模式只有一個實現類,State模式有多個;應用上,Proxy控制實現類的訪問,State模式動態改變實現類。
Proxy模式的示例代碼:
#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; }
// Forward calls to the implementation:
void f() { implementation->f(); }
void g() { implementation->g(); }
void h() { implementation->h(); }
};
int main() {
Proxy p;
p.f();
p.g();
p.h();
}
在某些情況下,Implementtation并不需要和類Proxy有相同的接口,這意味著Proxy類可以任意關聯Implementation類并將函數調用提交給它。使用共同接口的好處:可以把代理的替代物放到客戶代碼中,另外通過共同的接口,Iplementation被迫實現Proxy所需要的方法。代理模式用途:
Remote Proxy:遠程代理,為在不同的地址空間的對象提供代理,通過遠程代理對象實現。
Virtual Proxy:虛擬代理,即lazy initialization;
Protection Proxy:保護代理,如果不想客戶程序員擁有被代理對象的所有訪問權限時使用。
Smart Proxy:智能保護,renference counting引用計數就是一個離子,更簡單的是對特定函數進行引用計數。
State模式:產生一個可以改變其類的對象,它在所有的函數都有條件代碼時比較有用。
例子代碼:bool變量的實現
class Creature {
bool isFrog;
public:
Creature() : isFrog(true) {}
void greet() {
if(isFrog)
cout << "Ribbet!" << endl;
else
cout << "Darling!" << endl;
}
void kiss() { isFrog = false; }
};
int main() {
Creature creature;
creature.greet();
creature.kiss();
creature.greet();
}
所有的函數執行操作前都要測試isForg,通過State模式,就可以避免這樣的情況。
下面是用State模式實現的代碼:
#include <iostream>
#include <string>
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();
} ///:~