设计模式 Design Parttern ——代理模式Proxy http://blog.youkuaiyun.com/leeidea/ 1:头文件 #ifndef _PROXY_H_VANEY_ #define _PROXY_H_VANEY_ #include <iostream> using namespace std; /****************************************************************** 名称 :Proxy.h 版本 :1.00 描述 :演示代理模式的概念 作者 :vaney.li@gmail.com http://blog.youkuaiyun.com/leeidea 日期 :2010年10月22日 版权 :vaney.li@gmail.com http://blog.youkuaiyun.com/leeide ******************************************************************/ /* 官方解释:The Proxy provides a surrogate or place holder to provide access to an object. 我的理解:把本来直接访问A接口变成访问代理接口,代理接口再访问A接口 我的应用:WebService,800电话,10086,安全代理。 */ //抽象电话号码 class CTelephone { public: CTelephone() { cout << "CTelephone()" << endl; } virtual ~CTelephone() { cout << "~CTelephone()" << endl; } public: virtual void call() = 0; }; //具体电话号码 class C81221221 : public CTelephone { public: C81221221() { cout << "C81221221()" << endl; } virtual ~C81221221() { cout << "~C81221221()" << endl; } public: virtual void call() { cout << "C81221221 call()" << endl; } }; //代理号码 class C10086_is_Proxy : public CTelephone { CTelephone* tel; public: C10086_is_Proxy() { tel = 0; cout << "C10086_is_Proxy()" << endl; } virtual ~C10086_is_Proxy() { cout << "~C10086_is_Proxy()" << endl; } public: //打10086代理电话其实就是打81221221 virtual void call() { //当然你可以增加处理,比如选择空闲的客服小姐的电话号码 if(!tel) tel = new C81221221(); tel->call(); cout << "C10086_is_Proxy call()" << endl; } }; #define C_API extern "C" //用户 C_API int UsingPX(); #endif 2:源文件 #include "Proxy.h" C_API int UsingPX() { CTelephone* tel = new C10086_is_Proxy(); //打10086其实就是打移动公司内部电话,如81221221 tel->call(); return 1; } 3:用户文件main.c extern int UsingPX(); //系统默认入口 int _tmain(int argc, _TCHAR* argv[]) { return UsingPX(); }