代理模式 : 提供一种方式,控制对这个类访问。
举例 : 我们在运行系统时候,不能直接对这个系统进行访问,一般都需要增加用户名和密码。这个时候我们就要使用代理类,在代理类中增加用户名和密码 ,来控制对这个类的访问。
C++代码实现 :
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
class AbstractSystem {
public :
virtual void run() = 0;
};
class System : public AbstractSystem {
public:
virtual void run() {
cout<<"运行这个系统"<<endl;
}
};
class MyProxy : public AbstractSystem {
private :
string name;
string password;
System* sys;
public :
MyProxy(string name , string password) {
this->name = name;
this->password = password;
sys = new System();
}
~MyProxy() {
if (sys != NULL) {
delete sys;
}
}
bool Check() {
if (this->name == "root" && this->password == "123") {
return true;
}
return false;
}
virtual void run() {
if (Check()) {
this->sys->run();
}
else {
cout<<"用户名或者密码不正确"<<endl;
}
}
};
void test() {
AbstractSystem* myProxy = new MyProxy("root" , "123");
myProxy->run();
}
int main() {
test();
return 0;
}