Proxy模式真心是一個比較精巧的模式, 尤爲經過C++重載運算符(& ->),讓你瞬間對C++的感情重歸於好,忘記它的庫或者框架的缺少之痛苦.(另一個令其餘高級語言目瞪的是重載new/delete,來管理大塊內存). 對於Proxy自己來講, 它仍是涵蓋了多種模型,好比Remote Proxy, Virtual Proxy, Protection Proxy, and Smart Reference Proxy, 尤爲後者,對於編程技巧要求是比較高的.ios
評價: Proxy,屬於戰鬥精英級別, 在程序大規模應用的場景不如Strategy這些行爲模式,可是其理念仍是處於OOP的核心價值,因此很是重要.編程
區別,Adapter的目標於接口轉接,Decorator目標於接口的額外擴展, 而Proxy目標於對象代理,帶來額外的功能,好比遠程訪問,虛擬緩存,權限代理,和引用技術生命週期管理等.緩存
上純手打程序: app
// Proxy.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; //------- Remote Proxy------------------- class ClientWebService { public: void Login(){ cout << " Login to remove service." << endl;} void Logout() { cout << " logout. " <<endl;} }; class RemoteProxy { ClientWebService _remote; public: RemoteProxy(){ cout << "connecting.." << endl;} ~RemoteProxy(){ cout << "disconnectingg.." << endl;} void Login(){ _remote.Login(); } void Logout(){ _remote.Logout(); } }; //------- Virtual Proxy------------------- class Image { public: static Image* LoadImage(){ cout << "Load Image from Disk." << endl; return new Image(); } void Display(){} }; class VirtualProxy { Image* _image; public: void Display(){ _image = Image::LoadImage(); _image->Display(); } }; //------- Protection Proxy------------------- class RealObject { public: void Method(){ cout << "Real object called." << endl; } }; class ProtectionProxy { RealObject _real; public: void Method(char* user){ cout << "this object is allowed by " << user << endl; _real.Method(); } }; //-------Smart Reference Proxy for preexisint class ----------------- class ReferenceCounting { int _ref; public: ReferenceCounting(): _ref(1){} int add(){ cout << " add ref = " << _ref+1 << endl; return ++_ref; } int reduce(){ cout << " reduce ref = " << _ref-1 << endl; return --_ref; } }; template<class T> class auto_ptr { T* _p; ReferenceCounting* _ref; public: auto_ptr(T* p):_p(p), _ref(new ReferenceCounting()) {} ~auto_ptr(){ int ref = _ref->reduce(); if(ref == 0){ delete _p; delete _ref; } } auto_ptr(const auto_ptr& copy): _p(copy._p), _ref(copy._ref) { _ref->add(); } T* operator->(){ return _p;} T& operator&(){ return *_p;} auto_ptr& operator=(const auto_ptr& copy){ if(this != ©){ if(_ref){ if( 0 == _ref->reduce() ) delete _p; } _p = copy._p; _ref = copy._ref; _ref->add(); } return *this; } }; /* * Note: for smart pointer, there is still concurent access, this need synchoronized lock. * multiple reference usage to improve by inherit from reference counting class. */ // int main(int argc, char* argv[]) { RemoteProxy remote; remote.Login(); VirtualProxy imagePxy; imagePxy.Display(); ProtectionProxy protect; protect.Method("Jinbao"); /// Cant proxy twice or more. RemoteProxy* pRemote = new RemoteProxy(); auto_ptr<RemoteProxy> ap(pRemote); ap->Login(); auto_ptr<RemoteProxy> app = ap; app->Logout(); auto_ptr<RemoteProxy> appp(new RemoteProxy()); appp = app; return 0; }