1.Proxy Pattern最大的好处就是实现了逻辑和实现的彻底解耦。
2.Proxy Pattern结构图
3.实现
1 #ifndef _PROXY_H_ 2 #define _PROXY_H_ 3 4 class Subject 5 { 6 public: 7 virtual ~Subject(); 8 virtual void Request() = 0; 9 protected: 10 Subject(); 11 private: 12 }; 13 14 class ConcreteSubject:public Subject 15 { 16 public: 17 ConcreteSubject(); 18 ~ConcreteSubject(); 19 void Request(); 20 protected: 21 private: 22 }; 23 24 class Proxy:public Subject 25 { 26 public: 27 Proxy(); 28 Proxy(Subject* sub); 29 ~Proxy(); 30 void Request(); 31 protected: 32 private: 33 Subject* _sub; 34 }; 35 36 #endif
1 #include "Proxy.h" 2 #include <iostream> 3 using namespace std; 4 5 Subject::Subject() 6 { 7 8 } 9 Subject::~Subject() 10 { 11 12 } 13 ConcreteSubject::ConcreteSubject() 14 { 15 16 } 17 ConcreteSubject::~ConcreteSubject() 18 { 19 20 } 21 void ConcreteSubject::Request() 22 { 23 cout<<"ConcreteSubject......request ...."<<endl; 24 } 25 Proxy::Proxy() 26 { 27 28 } 29 Proxy::Proxy(Subject* sub) 30 { 31 _sub = sub; 32 } 33 Proxy::~Proxy() 34 { 35 delete _sub; 36 } 37 void Proxy::Request() 38 { 39 cout<<"Proxy request...."<<endl; 40 _sub->Request(); 41 }
1 #include "Proxy.h" 2 #include <iostream> 3 using namespace std; 4 5 int main(int argc,char* argv[]) 6 { 7 Subject* sub = new ConcreteSubject(); 8 Proxy* p = new Proxy(sub); 9 p->Request(); 10 return 0; 11 }