C++设计模式编程中proxy代理模式的使用实例

代理模式典型的结构图为:

实际上,代理模式的想法非常简单。

代理模式的实现:

完整代码示例(code):代理模式的实现很简单,这里为了方便初学者的学习和参考,将给出完整的实现代码(所有代码采用 C++实现,并在 VC 6.0 下测试运行)。

代码片断 1:Proxy.h

//Proxy.h
#ifndef _PROXY_H_
#define _PROXY_H_
class Subject{
  public:
  virtual ~Subject();
  virtual void Request() = 0;
  protected:
  Subject();
  private:
};
class ConcreteSubject:public Subject{
  public:
  ConcreteSubject();
  ~ConcreteSubject();
  void Request();
  protected:
  private:
};
class Proxy{
  public:
  Proxy();
  Proxy(Subject* sub);
  ~Proxy();
  void Request();
  protected:
  private:
  Subject* _sub;
};
#endif //~_PROXY_H_

代码片断 2:Proxy.cpp

//Proxy.cpp
#include "Proxy.h"
#include <iostream>
using namespace std;
Subject::Subject(){
}
Subject::~Subject(){
}
ConcreteSubject::ConcreteSubject(){
}
ConcreteSubject::~ConcreteSubject(){
}
void ConcreteSubject::Request(){
  cout<<"ConcreteSubject......request
  ...."<<endl;
}
Proxy::Proxy(){
}
Proxy::Proxy(Subject* sub){
  _sub = sub;
}
Proxy::~Proxy(){
  delete _sub;
}
void Proxy::Request(){
  cout<<"Proxy request...."<<endl;
  _sub->Request();
}

代码片断 3:main.cpp

//main.cpp
#include "Proxy.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[]){
   Subject* sub = new ConcreteSubject();
  Proxy* p = new Proxy(sub);
  p->Request();
  return 0;
}

代码说明:代理模式的实现很简单,这里不做多余解释。可以看到,示例代码运行后,p 的 Request 请求实际上是交给了 sub 来实际执行。

再来看一个例子:

#include <iostream> 
#include <string> 
using namespace std; 
 
class Receiver 
{ 
private: 
  string name; 
 
public: 
  Receiver(string name):name(name) 
  { 
 
  } 
  string GetName() 
  { 
    return name; 
  } 
}; 
 
class Subject 
{ 
public: 
  virtual void display(){} 
}; 
 
class Sender:public Subject 
{ 
  Receiver *someone; 
public: 
  void SetReceiver(Receiver *someone) 
  { 
    this->someone = someone; 
  } 
  virtual void display() 
  { 
    cout<<"i hate you:" << someone->GetName()<<endl; 
  } 
}; 
 
class Proxy:public Subject 
{ 
public: 
  Subject *realobject; 
 
  void SetClient(Subject *client) 
  { 
    this->realobject = client; 
  } 
 
  void display() 
  { 
    realobject->display(); 
  } 
}; 
 
int main() 
{ 
  Receiver *recv = new Receiver("nobody"); 
  Sender *obj  = new Sender; 
  obj->SetReceiver(recv); 
  Proxy *proxy = new Proxy; 
  proxy->SetClient(obj); 
 
  proxy->display(); 
 
  system("pause"); 
  return 0; 
} 

由此可见,代理模式最大的好处就是实现了逻辑和实现的彻底解耦。