设计模式之代理模式

 

代理模式 : 提供一种方式,控制对这个类访问。

举例 : 我们在运行系统时候,不能直接对这个系统进行访问,一般都需要增加用户名和密码。这个时候我们就要使用代理类,在代理类中增加用户名和密码 ,来控制对这个类的访问。

 

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值