Fork me on GitHub

设计模式——代理模式(C++实现)

 

     

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 
 7 class CSubject
 8 {
 9 public:
10         virtual void Request() = 0;
11 };
12 
13 class CRealSubject: public CSubject
14 {
15 public:
16         virtual void Request()
17         {
18                 cout<< "ReadSubject request....."<< endl;
19         }
20 
21 };
22 
23 class CProxy: public CSubject
24 {
25 public:
26         CProxy()
27         {
28                 m_pstRealSubject = new CRealSubject();
29         }
30 
31         virtual void Request()
32         {
33                 if (m_pstRealSubject == NULL)
34                         m_pstRealSubject = new CRealSubject();
35 
36                 cout<< "CProxy Request...."<< endl;
37                 m_pstRealSubject->Request();
38         }
39 
40 private:
41         CRealSubject* m_pstRealSubject;
42 };
43 
44 
45 int main(int argc, char* argv[])
46 {
47         CProxy* pstProxy = new CProxy();
48         pstProxy->Request();
49 
50         return 0;
51 }
52 /////////////////////////////////////
53 [root@ ~/learn_code/design_pattern/5_proxy]$ ./proxy       
54 CProxy Request....
55 ReadSubject request.....

 

 

参考:http://design-patterns.readthedocs.io/zh_CN/latest/structural_patterns/proxy.html

 

posted @ 2017-04-28 21:20  码农的逼格  阅读(605)  评论(0编辑  收藏  举报