设计模式(5) 代理模式

  • 代理模式:一个类代表另一个类的功能,为其他对象提供一种代理以控制对这个对象的访问。
  • 直接访问对象时带来的问题,比如说:要访问的对象在远程的机器上。在面向对象系统中,有些对象由于某些原因(比如对象创建开销很大,或者某些操作需要安全控制,或者需要进程外的访问),直接访问会给使用者或者系统结构带来很多麻烦,我们可以在访问此对象时加上一个对此对象的访问层。
    在这里插入图片描述

#include<iostream>
#include<string>
using namespace std;

class AbstractCommonInterface
{
    
    
	virtual void run()=0;
};

class MySystem:public AbstractCommonInterface
{
    
    
public:
	virtual void run()
	{
    
    
		cout<<"系统启动"<<endl;
	}
};
//因为MySystem需要权限的验证,并不是所有人都能来调用run
//只能通过代理类来run
//那么代理类和MySystem类:需要有一个共有的接口
//就像工厂和超市都卖水,超市是工厂的一个代理
//所以我们通过代理来验证用户名和密码
class MySystemProxy:public AbstractCommonInterface
{
    
    
public:
	MySystemProxy(string username,string password)
	{
    
    
		this->m_UserName=username;
		this->m_Password=password;
		proxy_MySystem=new MySystem;//将MySystem封装出来供MySystemProxy使用
	}

	//判断是否拥有权限
	bool check_UsernameAndPassword()
	{
    
    
		if(m_UserName=="admin"&& m_Password=="admin")
		{
    
    
			return true;
		}
		return false;
	}

	virtual void run()
	{
    
    
		if(check_UsernameAndPassword())
		{
    
    
			cout<<"验证成功!"<<endl;
			this->proxy_MySystem->run();
		}
		else
		{
    
    
			cout<<"用户名或密码错误!"<<endl;
		}
	}

	~MySystemProxy()
	{
    
    
		if(proxy_MySystem!=NULL)
		{
    
    
			delete proxy_MySystem;
			proxy_MySystem=NULL;
		}
	}
public:
	MySystem* proxy_MySystem;//将MySystem封装出来供MySystemProxy使用
	string m_UserName;
	string m_Password;
};

void test()
{
    
    
	MySystemProxy* systemProxy1=new MySystemProxy("root","123");
	systemProxy1->run();

	MySystemProxy* systemProxy2=new MySystemProxy("admin","admin");
	systemProxy2->run();
}

int main()
{
    
    
	test();
	system("pause");
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_41363459/article/details/111242858