普通代理:访问真实对象,通过代理对象来放问真实对象;
实现方法:
(1)创建代理对象时,传递一个真实对象的引用;
(2)在代理类内部实现,在代理类创建时,由代理类决定创建一个真实角色;
// 签字
class ISign{
public:
virtual void doSomeThing(string msg) = 0;
};
// 老板
class Boss : public ISign{
public:
virtual void doSomeThing(string msg){
cout << "Boss: " << msg << endl;
}
};
// 秘书代理
class SecretaryProxy : public ISign{
public:
// 普通代理: 方法1
SecretaryProxy(){
boss = new Boss();
}
SecretaryProxy(Boss* 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:
Boss* boss;
};
int main(){
SecretaryProxy* proxy_1 = new SecretaryProxy();
proxy_1->doSomeThing("hello");
Boss* boss = new Boss();
SecretaryProxy* proxy_2 = new SecretaryProxy(boss);
proxy_2->doSomeThing("hello");
return 0;
}