C++代理模式
主要根据代理模式整理,感谢作者分享!
[DP]上的定义:为其他对象提供一种代理以控制对这个对象的访问。有四种常用的情况:(1)远程代理,(2)虚代理,(3)保护代理,(4)智能引用。本文主要介绍虚代理和智能引用两种情况。
考虑一个可以在文档中嵌入图形对象的文档编辑器。有些图形对象的创建开销很大。但是打开文档必须很迅速,因此我们在打开文档时应避免一次性创建所有开销很大的对象。这里就可以运用代理模式,在打开文档时,并不打开图形对象,而是打开图形对象的代理以替代真实的图形。待到真正需要打开图形时,仍由代理负责打开。这是[DP]一书上的给的例子。下面给出代理模式的UML图。
1 #include <bits/stdc++.h> 2 //#include "solution.h" 3 using namespace std; 4 5 #define debug(x) cout << #x << " at line " << __LINE__ << " is: " << x << endl 6 7 class CImage 8 { 9 public: 10 virtual ~CImage(){cout << "~CImage()\n";} 11 virtual void Show(){} 12 protected: 13 CImage(string imgName): m_imgName(imgName){cout << "CImage()\n";} 14 string m_imgName; 15 }; 16 17 //concrete implement 18 class CBigImage : public CImage 19 { 20 public: 21 CBigImage(string imgName): CImage(imgName), m_bigImgName(imgName){ 22 cout << "CBigImage()\n"; 23 } 24 ~CBigImage(){ 25 cout << "~CBigImage()\n"; 26 } 27 void Show(){cout << "show big image" <<endl;} 28 protected: 29 string m_bigImgName; 30 }; 31 32 // proxy 33 class CBigImageProxy : public CImage 34 { 35 public: 36 CBigImageProxy(string imgName): CImage(imgName), m_img(NULL), m_bigImgName(imgName){ 37 cout << "CBigImageProxy()\n"; 38 } 39 ~CBigImageProxy(){ 40 if(NULL != m_img){ 41 delete m_img; 42 m_img = NULL; 43 } 44 cout << "~CBigImageProxy()\n"; 45 } 46 void Show(){ 47 if(NULL == m_img){ 48 m_img = new CBigImage(m_bigImgName); 49 } 50 m_img->Show(); 51 } 52 private: 53 CImage *m_img; 54 string m_bigImgName; 55 }; 56 57 58 class Subject 59 { 60 public: 61 virtual ~Subject(){cout << "~Subject()\n";} 62 virtual void Request()=0; 63 protected: 64 Subject(){cout << "Subject()\n";} 65 }; 66 67 68 class ConcreteSubject : public Subject 69 { 70 public: 71 ConcreteSubject(){ 72 cout << "ConcreteSubject()\n"; 73 } 74 ~ConcreteSubject(){ 75 cout << "~ConcreteSubject()\n"; 76 } 77 virtual void Request(){cout << "ConcreteSubject Request()\n";} 78 }; 79 80 class Proxy : public Subject 81 { 82 public: 83 Proxy(){ 84 cout << "Proxy()\n"; 85 this->m_sub = new ConcreteSubject(); 86 } 87 // Proxy(Subject* _sub):m_sub(_sub){ 88 // cout << "Proxy(Subject)\n"; 89 // } 90 91 virtual void Request()//实现对委托者的委托任务执行与补偿 92 { 93 this->m_sub->Request(); 94 } 95 ~Proxy(){ 96 if(NULL != this->m_sub){ 97 delete this->m_sub; 98 this->m_sub = NULL; 99 } 100 cout << "~Proxy()" << endl; 101 } 102 103 private: 104 Subject *m_sub; 105 }; 106 107 108 int main(int argc, char *argv[]) 109 { 110 CBigImageProxy *bip = new CBigImageProxy("proxy.jpg"); 111 bip->Show(); 112 delete bip; 113 bip = NULL; 114 115 Proxy *py = new Proxy(); 116 py->Request(); 117 delete py; 118 py = NULL; 119 return 0; 120 } 121 // g++ -g -Wall main.cpp -o xmain
至于智能指针,建议可以参考C++11标准的智能指针。