学了C++基本的语法都知道继承可以让子类拥有更多的功能,除了继承还有组合,委托,也能让一个类的功能增加。设计模式,这个设计是设计继承,组合,委托,之间相互叠加的方式,让其符合业务需求。 代理模式相对简单很多,当然这需要你对委托熟悉。在一个类中,把另一个类的对象指针作为它的数据成员,在访问这个成员前,需要满足一定的条件,很简单,直接看代码。 实测有效,可直接运行。
Exe : Proxy.o
g++ -o Exe Proxy.o
main.o : Proxy.cpp
g++ -c -g Proxy.cpp
clean :
rm Proxy
#include <iostream>
#include <string>
using namespace std;
//代理模式
class MySystem
{
public:
void run();
};
void MySystem::run()
{
cout << "the System is running!" << endl;
}
class MySystem_Proxy : public MySystem
{
public:
MySystem_Proxy(string name, string PW);
bool check();
void run();
string name;
string PW;
MySystem* p_MySystem = NULL;
};
MySystem_Proxy::MySystem_Proxy(string name, string PW)
{
this->name = name;
this->PW = PW;
p_MySystem = new MySystem;
}
bool MySystem_Proxy::check()
{
if(name == "admin" && PW == "123456")
{
return true;
}
else
{
return false;
}
}
void MySystem_Proxy::run()
{
if(check() == true)
{
p_MySystem->run();
}
else
{
cout << "Please check your username or password!" << endl;
}
}
int main(void)
{
MySystem_Proxy* p_MySystem_Proxy = new MySystem_Proxy("admin", "123456");
p_MySystem_Proxy->run();
return 0;
}