代理模式给某一个对象提供一个代理,并由代理对象控制对原对象的引用。
- 在面向对象系统中,有些对象由于某种原因(比如对象创建的开销很大,或者某些操作需要安全控制,或者需要进程外的访问等), 直接访问会给使用者、或者系统结构带来很多麻烦。
- 如何在不失去透明操作对象的同事来管理/控制这些对象特有的复杂性?增加一层间接层是软件开发中常见的解决方式。
模式定义:
为其他对象提供一种代理以控制(隔离,使用接口)对这对象的访问。 ——《设计模式》GoF
#include<iostream>
#include<string>
using namespace std;
//抽象系统类
class AbstractCommonInterface{
public:
virtual void run() = 0;
};
//我已经写好的系统
class MySystem :public AbstractCommonInterface{
public:
virtual void run(){
cout << "系统启动..." << endl;
}
};
//必须有要权限验证,不是所有人都能来启动我的启动,提供用户名和密码
class MrSystemProxy:public AbstractCommonInterface{
public:
MySystem*pSystem;
string mUsername;
string mPassword;
public:
MrSystemProxy(string username, string password){
this->mUsername = username;
this->mPassword = password;
pSystem = new MySystem;
}
~MrSystemProxy(){
if (pSystem != NULL) {
delete pSystem;
}
}
bool checkUsernameAndPassoword(){
if (mUsername == "admin" && mPassword == "admin"){
return true;
}
return false;
}
virtual void run(){
if (checkUsernameAndPassoword()){
cout << "用户名和密码正确,验证通过." << endl;
this->pSystem->run();
}
else{
cout << "用户名或者密码错误,权限不足." << endl;
}
}
};
void test01() {
MrSystemProxy* proxy = new MrSystemProxy("root", "admin");
proxy->run();
delete proxy;
proxy = new MrSystemProxy("admin", "admin");
proxy->run();
delete proxy;
}
int main()
{
test01();
return 0;
}

京公网安备 11010502036488号