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

时间:2022-05-30 19:16:34

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

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

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

代理模式的实现:

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

代码片断 1:Proxy.h

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
//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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//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

?
1
2
3
4
5
6
7
8
9
10
//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 来实际执行。

再来看一个例子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#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;
}

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