代理模式
强制代理:
真实角色必须通过代理才能访问,并且真实角色的代理的产生,也必须由真实角色决定,与普通代理正好相反;
// 签字
class ISign{
public:
virtual void doSomeThing(string msg) = 0;
};
// 秘书代理
class SecretaryProxy;
// 老板
class Boss : public ISign{
public:
virtual void doSomeThing(string msg){
if(proxy == NULL)
cout << "please access secretary" << endl;
else
cout << "Boss: " << msg << endl;
}
ISign* getProxy();
private:
ISign* proxy;
};
// 秘书代理
class SecretaryProxy : public ISign{
public:
SecretaryProxy(ISign* boss){
this->boss = boss;
}
virtual void doSomeThing(string msg){
cout << "SecretaryProxy: do pre something: " << endl;
boss->doSomeThing(msg);
cout << "SecretaryProxy: do after something: " << endl;
}
private:
ISign* boss;
};
ISign* Boss::getProxy(){
proxy = new SecretaryProxy(this);
return proxy;
}
int main(){
Boss* boss = new Boss();
ISign* proxy = boss->getProxy();
proxy->doSomeThing("hello");
return 0;
}