代理模式是指为其他对象提供代理来控制对象的访问。这种手段有时候可以给我们带来许多好处。如:通过代理可以实现异步响应处理;通过代理可以起到保护或限制对象的使用的作用,从而提高安全性。
在设计上,用户使用代理对象与直接使用被代理对象,应该没什么差异。因此,代理对象的设计,需要实现被代理对象的相应接口。模式的类关系结构图参考如下:
模式的编码结构参考如下:
1 namespace proxy 2 { 3 class Target 4 { 5 public: 6 virtual void action() {} 7 8 };//class Target 9 10 class ConcreteTarget : public Target 11 { 12 public: 13 virtual void action() { /*some code here........*/ } 14 15 };//class ConcreteTarget 16 17 class ProxyTarget : public Target 18 { 19 public: 20 virtual void action() { 21 // do everything that you want to do. 22 // such as: you can call _target->action() directly. 23 // such as: you can do nothing here........ 24 // such as: ........ 25 } 26 27 private: 28 ConcreteTarget* _target; 29 30 };//class ProxyTarget 31 32 }//namespace proxy