C++模式-Proxy

代理模式:为其他对象提供一种代理以控制对这个对象的访问。

代理模式:⒈远程代理  也就是为一个对象在不同的地址空间提供局部代表。这样可以隐藏一个对象存在于不同地址空间的事实(例如WEBSERVICES)

⒉虚拟代理  是根据需要创建开销很大的对象。通过它来存放实例化需要很长时间的真实对象(例如网页中的图片,通过虚拟代理来替代真实的图片,此时代理存储真实图片的路径和尺寸)

⒊安全代理  用来控制真实对象访问时的权限

⒋智能指引  指当调用真实对象时,代理处理另外一些事

 

类实现

 

  1. //Proxy.h  
  2. #ifndef AFX_CLASS_SUBJECT  
  3. #define AFX_CLASS_SUBJECT  
  4. class Subject  
  5. {  
  6. public:  
  7.     virtual void Request()=0;  
  8. };  
  9. #endif  
  10.   
  11. #ifndef AFX_CLASS_REALSUBJECT  
  12. #define AFX_CLASS_REALSUBJECT  
  13. class RealSubject:public Subject  
  14. {  
  15. public:  
  16.     virtual void Request()  
  17.     {  
  18.         cout<< "真实的请求" << endl;  
  19.     }  
  20. };  
  21. #endif  
  22.   
  23. #ifndef AFX_CLASS_PROXY  
  24. #define AFX_CLASS_PROXY  
  25. class Proxy:public Subject  
  26. {  
  27. public:  
  28.     Proxy()  
  29.     {  
  30.         realSubject = NULL;  
  31.     }  
  32.     virtual void Request()  
  33.     {  
  34.         if( realSubject == NULL )  
  35.         {  
  36.             realSubject = new RealSubject();  
  37.         }  
  38.         realSubject->Request();  
  39.     }  
  40. private:  
  41.     RealSubject *realSubject;  
  42. };  
  43. #endif  

 

 

主函数实现:

 

  1. #include <iostream>  
  2. #include <string>  
  3. #include <conio.h>  
  4. using namespace std;  
  5. #include "proxy.h"  
  6.   
  7. int main( int argc , char *argv[] )  
  8. {  
  9.     Proxy *proxy = new Proxy();  
  10.     proxy->Request();  
  11.   
  12.     getch();  
  13.     return 1;  
  14. }  

 

posted @ 2012-05-31 01:31  姚康  阅读(1068)  评论(1编辑  收藏  举报