为其他对象提供一种代理以控制对这个对象的访问。在某些情况下。一个对象不适合或者不能直接引用另一个对象。代理在它们中起到中介的作用。
常见代理:代理服务器,缓冲服务器
#include <iostream>
using namespace std;
class AbstractInterface{
public:
virtual void run()=0;
};
class MySystem:AbstractInterface{
public:
virtual void run(){
cout<<"System runing"<<endl;
}
};
class MySystemProxy:public AbstractInterface{
public:
MySystemProxy(string username,string passwd){
this->passWord = passwd;
this->userName = username;
pSystem = new MySystem;
}
bool checkUserAndPassword(){
if(userName == "admin" && passWord == "admin"){
return true;
}
return false;
}
virtual void run(){
if(checkUserAndPassword()){
this->pSystem->run();
}
else{
cout<<"userName or passWord error"<<endl;
}
}
~MySystemProxy(){
if(pSystem!=NULL){
delete pSystem;
}
}
public:
MySystem* pSystem;
string userName;
string passWord;
};
int main(int argc, char *argv[])
{
//通过代理启动服务。
MySystemProxy* proxy = new MySystemProxy("11","22");
proxy->run();
proxy = new MySystemProxy("admin","admin");
proxy->run();
return 0;
}