Design pattern (5) Agent pattern

  • Proxy mode: One class represents the function of another class and provides a proxy for other objects to control access to this object.
  • Now 直接访问对象时带来的问题, for example: the object to be accessed is on a remote machine. In an object-oriented system, for certain reasons (for example, object creation is expensive, or certain operations require security control, or need out-of-process access), direct access will bring a lot of trouble to the user or the system structure. We can add an access layer to this object when we access this object.
    Insert picture description here

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


Guess you like

Origin blog.csdn.net/qq_41363459/article/details/111242858