设计模式-代理模式

结构型-代理模式

//代理模式:为其他对象提供一种代理以控制对这个对象的访问

#include <iostream>
using namespace std;

//提供一种代理来控制对其他对象的访问
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->mUsername = username;
        this->mPassword = password;
        pSystem = new MySystem;
    }

    bool checkUsernameAndPassword(){
        if(mUsername == "admin" && mPassword == "admin"){
            return true;
        }
        return false;
    }

    virtual void run(){
        if(checkUsernameAndPassword()){
            cout << "用户名和密码正确,验证通过...";
            this->pSystem->run();
        }else{
            cout << "用户名和密码错误,权限不足...";
        }
    }

    ~MySystemProxy(){
        if(pSystem != NULL){
            delete pSystem;
        }
    }
public:
    MySystem* pSystem;
    string mUsername;
    string mPassword;
};

void test01(){
    MySystemProxy* proxy = new MySystemProxy("admin", "admin");
    proxy->run();
}

int main()
{
    test01();


    system("pause");
    return 0;
}

posted @ 2023-10-14 19:15  洋綮  阅读(6)  评论(0)    收藏  举报