代理模式的定义:为其他对象提供了一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
在生活中 代理模式的例子有很多 比如我们想要访问外网youtube 但是无法直接访问 就需要用到代理服务器 或者说当很多很同时向一个网页发起请求的时候会变得很卡 这时候可以在中间设置一个代理服务器处理延迟初始化和缓存查询结果的工作
原文链接:https://blog.csdn.net/weixin_43754049/article/details/125895707
![](https://img-blog.csdnimg.cn/img_convert/5fdbeef61ff55ca468dab60a3cca829b.png)
#include <iostream>
using namespace std;
//代理模式: 提供一个代理来控制对其他对象的访问
//提供一个公共接口 来约束 代理系统和真实系统必须都包含run()方法
class AbstractCommonInterface {
public:
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->mUsernmae = username;
this->mPassword = password;
pSystem = new MySystem;
}
bool checkUsernameAndPassword() {
if (mUsernmae == "admin" && mPassword == "admin") {
return true;
}
return false;
}
virtual void run() {
if (checkUsernameAndPassword()) {
cout << "用户名和密码正确,验证通过" << endl;
this->pSystem->run();
}
else {
cout << "用户名或密码错误 权限不足" << endl;
}
}
~MySystemProxy() {
if (pSystem != NULL) {
delete pSystem;
}
}
private:
//代理类中有一个系统指针变量
MySystem* pSystem;
string mUsernmae;
string mPassword;
};
void test01() {
MySystemProxy* proxy = new MySystemProxy("admin","admin");
proxy->run();
delete proxy;
proxy = new MySystemProxy("wrong","admin");
proxy->run();
delete proxy;
}
int main() {
test01();
return 0;
}
![](https://img-blog.csdnimg.cn/img_convert/542ee4f9b8d1d18c34e849ace4a9f996.png)