学了C++基本的语法都知道继承可以让子类拥有更多的功能,除了继承还有组合,委托,也能让一个类的功能增加。设计模式,这个设计是设计继承,组合,委托,之间相互叠加的方式,让其符合业务需求。
代理模式相对简单很多,当然这需要你对委托熟悉。在一个类中,把另一个类的对象指针作为它的数据成员,在访问这个成员前,需要满足一定的条件,很简单,直接看代码。
这些代码都是在学习这些的过程中码的。。。。。
上代码,亲测有效!
#include <iostream>
#include <string>
using namespace std;
//提供一种代理控制对其他对象的访问
class MySystem
{
public:
virtual void run()
{
cout << "启动系统..." << endl;
}
};
class MySystemProxy
{
public:
MySystemProxy(string userName, string passWard)
{
this->m_PassWord = userName;
this->m_UserName = passWard;
this->pSystem = new MySystem;
}
bool check()
{
if (m_UserName == "admin" && m_PassWord == "admin")
{
return true;
}
return false;
}
void run()
{
//满足登录条件才能启动系统
//代理是对真正系统的管理
if (check())
{
cout << "登录成功" << endl;
this->pSystem->run();
}
else
{
cout << "用户名或密码错误" << endl;
}
}
~MySystemProxy()
{
if (this->pSystem != NULL)
{
delete this->pSystem;
}
}
//代理要能完成系统的所有功能
//因此需要拿到系统的对象指针
MySystem* pSystem;
string m_UserName;
string m_PassWord;
};
//必须要有权限的验证才能启动系统
//提供用户名和密码
//代理就是系统
void test01()
{
MySystemProxy* proxy = new MySystemProxy("admin", "admin");
proxy->run();
}
int main(void)
{
test01();
system("pause");
return 0;
}