C++設計形式編程中proxy署理形式的應用實例。本站提示廣大學習愛好者:(C++設計形式編程中proxy署理形式的應用實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++設計形式編程中proxy署理形式的應用實例正文
署理形式典范的構造圖為:
現實上,署理形式的設法主意異常簡略。
署理形式的完成:
完全代碼示例(code):署理形式的完成很簡略,這裡為了便利初學者的進修和參考,將給出完全的完成代碼(一切代碼采取 C++完成,並在 VC 6.0 下測試運轉)。
代碼片段 1:Proxy.h
//Proxy.h #ifndef _PROXY_H_ #define _PROXY_H_ class Subject{ public: virtual ~Subject(); virtual void Request() = 0; protected: Subject(); private: }; class ConcreteSubject:public Subject{ public: ConcreteSubject(); ~ConcreteSubject(); void Request(); protected: private: }; class Proxy{ public: Proxy(); Proxy(Subject* sub); ~Proxy(); void Request(); protected: private: Subject* _sub; }; #endif //~_PROXY_H_
代碼片段 2:Proxy.cpp
//Proxy.cpp #include "Proxy.h" #include <iostream> using namespace std; Subject::Subject(){ } Subject::~Subject(){ } ConcreteSubject::ConcreteSubject(){ } ConcreteSubject::~ConcreteSubject(){ } void ConcreteSubject::Request(){ cout<<"ConcreteSubject......request ...."<<endl; } Proxy::Proxy(){ } Proxy::Proxy(Subject* sub){ _sub = sub; } Proxy::~Proxy(){ delete _sub; } void Proxy::Request(){ cout<<"Proxy request...."<<endl; _sub->Request(); }
代碼片段 3:main.cpp
//main.cpp #include "Proxy.h" #include <iostream> using namespace std; int main(int argc,char* argv[]){ Subject* sub = new ConcreteSubject(); Proxy* p = new Proxy(sub); p->Request(); return 0; }
代碼解釋:署理形式的完成很簡略,這裡不做過剩說明。可以看到,示例代碼運轉後,p 的 Request 要求現實上是交給了 sub 來現實履行。
再來看一個例子:
#include <iostream> #include <string> using namespace std; class Receiver { private: string name; public: Receiver(string name):name(name) { } string GetName() { return name; } }; class Subject { public: virtual void display(){} }; class Sender:public Subject { Receiver *someone; public: void SetReceiver(Receiver *someone) { this->someone = someone; } virtual void display() { cout<<"i hate you:" << someone->GetName()<<endl; } }; class Proxy:public Subject { public: Subject *realobject; void SetClient(Subject *client) { this->realobject = client; } void display() { realobject->display(); } }; int main() { Receiver *recv = new Receiver("nobody"); Sender *obj = new Sender; obj->SetReceiver(recv); Proxy *proxy = new Proxy; proxy->SetClient(obj); proxy->display(); system("pause"); return 0; }
因而可知,署理形式最年夜的利益就是完成了邏輯和完成的完全解耦。