- 代理模式:一个类代表另一个类的功能,为其他对象提供一种代理以控制对这个对象的访问。
- 在
直接访问对象时带来的问题
,比如说:要访问的对象在远程的机器上。在面向对象系统中,有些对象由于某些原因(比如对象创建开销很大,或者某些操作需要安全控制,或者需要进程外的访问),直接访问会给使用者或者系统结构带来很多麻烦,我们可以在访问此对象时加上一个对此对象的访问层。
#include<iostream>
#include<string>
using namespace std;
class AbstractCommonInterface
{
virtual void run()=0;
};
class MySystem:public AbstractCommonInterface
{
public:
virtual void run()
{
cout<<"系统启动"<<endl;
}
};
class MySystemProxy:public AbstractCommonInterface
{
public:
MySystemProxy(string username,string password)
{
this->m_UserName=username;
this->m_Password=password;
proxy_MySystem=new MySystem;
}
bool check_UsernameAndPassword()
{
if(m_UserName=="admin"&& m_Password=="admin")
{
return true;
}
return false;
}
virtual void run()
{
if(check_UsernameAndPassword())
{
cout<<"验证成功!"<<endl;
this->proxy_MySystem->run();
}
else
{
cout<<"用户名或密码错误!"<<endl;
}
}
~MySystemProxy()
{
if(proxy_MySystem!=NULL)
{
delete proxy_MySystem;
proxy_MySystem=NULL;
}
}
public:
MySystem* proxy_MySystem;
string m_UserName;
string m_Password;
};
void test()
{
MySystemProxy* systemProxy1=new MySystemProxy("root","123");
systemProxy1->run();
MySystemProxy* systemProxy2=new MySystemProxy("admin","admin");
systemProxy2->run();
}
int main()
{
test();
system("pause");
return 0;
}