學(xué)了C++基本的語(yǔ)法都知道繼承可以讓子類(lèi)擁有更多的功能,除了繼承還有組合,委托,也能讓一個(gè)類(lèi)的功能增加。設(shè)計(jì)模式,這個(gè)設(shè)計(jì)是設(shè)計(jì)繼承,組合,委托,之間相互疊加的方式,讓其符合業(yè)務(wù)需求。
代理模式相對(duì)簡(jiǎn)單很多,當(dāng)然這需要你對(duì)委托熟悉。在一個(gè)類(lèi)中,把另一個(gè)類(lèi)的對(duì)象指針作為它的數(shù)據(jù)成員,在訪問(wèn)這個(gè)成員前,需要滿(mǎn)足一定的條件,很簡(jiǎn)單,直接看代碼。
實(shí)測(cè)有效,可直接運(yùn)行。
Exe : Proxy.o g++ -o Exe Proxy.omain.o : Proxy.cpp g++ -c -g Proxy.cppclean : rm Proxy
#include #include 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;}