C++設(shè)計(jì)模式編程中proxy代理模式的使用實(shí)例
代理模式典型的結(jié)構(gòu)圖為:
實(shí)際上,代理模式的想法非常簡單。
代理模式的實(shí)現(xiàn):
完整代碼示例(code):代理模式的實(shí)現(xiàn)很簡單,這里為了方便初學(xué)者的學(xué)習(xí)和參考,將給出完整的實(shí)現(xiàn)代碼(所有代碼采用 C++實(shí)現(xiàn),并在 VC 6.0 下測(cè)試運(yùn)行)。
代碼片斷 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; }
代碼說明:代理模式的實(shí)現(xiàn)很簡單,這里不做多余解釋??梢钥吹剑纠a運(yùn)行后,p 的 Request 請(qǐng)求實(shí)際上是交給了 sub 來實(shí)際執(zhí)行。
再來看一個(gè)例子:
#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; }
由此可見,代理模式最大的好處就是實(shí)現(xiàn)了邏輯和實(shí)現(xiàn)的徹底解耦。
相關(guān)文章
C++ 實(shí)現(xiàn)靜態(tài)鏈表的簡單實(shí)例
這篇文章主要介紹了C++ 實(shí)現(xiàn)靜態(tài)鏈表的簡單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-06-06C/C++?Qt?數(shù)據(jù)庫QSql增刪改查組件應(yīng)用教程
Qt?SQL模塊是Qt中用來操作數(shù)據(jù)庫的類,該類封裝了各種SQL數(shù)據(jù)庫接口,可以很方便的鏈接并使用。本文主要介紹了Qt數(shù)據(jù)庫QSql增刪改查組件的應(yīng)用教程,感興趣的同學(xué)可以學(xué)習(xí)一下2021-12-12C語言實(shí)現(xiàn)五子棋人人對(duì)戰(zhàn)
這篇文章主要為大家詳細(xì)介紹了C語言實(shí)現(xiàn)五子棋人人對(duì)戰(zhàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12求32位機(jī)器上unsigned int的最大值及int的最大值的解決方法
本篇文章是對(duì)求32位機(jī)器上unsigned int的最大值及int的最大值的解決方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05