码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 代理模式

时间:2014-07-02 19:22:40      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   代码   c++   

  刚刚看到了C++代理模式,简单的学习了一下,当一个应用程序执行时,可以采用这种方法,至于到底怎么用,我还不知道。

  A->B->C。

  当应用A要执行的时候,采用代理B,B继承自协议C,实现C中的虚方法,C为一个抽象类,包含一个纯虚函数。这样的话,主函数中只需要执行A的方法就可以了。

  下面用代码简单演示下上述过程。

  协议类Aprotol:  

 1 #ifndef _APROTOL_H
 2 #define _APROTOL_H
 3 
 4 class Aprotol
 5 {
 6 public:
 7     virtual void DoSomething()=0;
 8 };
 9 
10 #endif

  代理类Delegate:

 1 #ifndef _DELEGATE_H
 2 #define _DELEGATE_H
 3 
 4 #include"Aprotol.h"
 5 #include<iostream>
 6 using namespace std;
 7 
 8 class Delegate:public Aprotol
 9 {
10 public:
11     void DoSomething();
12 };
13 
14 void Delegate::DoSomething()
15 {
16     cout<<"程序从这里开始....do something\n";
17 }
18 #endif

  应用类Application:

 1 #ifndef _APPLICATION_H
 2 #define _APPLICATION_H
 3 
 4 #include"Delegate.h"
 5 class Application
 6 {
 7 public:
 8     Delegate * del;
 9     void set(Delegate *del)
10     {
11         this->del=del;
12     }
13     void run()
14     {
15         this->del->DoSomething();
16     }
17 };
18 
19 #endif

  main函数:

 1 #include"Application.h"
 2 #include"Aprotol.h"
 3 #include"Delegate.h"
 4 
 5 int main()
 6 {
 7     Delegate *a=new Delegate;
 8     Application *b=new Application;
 9     b->set(a);
10     b->run();
11     return 0;
12 }

  这样写话,清晰明了,主函数的程序不需要修改,我们只需要修改协议的方法即可。这里只是解释了一下这种思路,希望以后在实际用到的时候能有新的体会和见解。

C++ 代理模式,布布扣,bubuko.com

C++ 代理模式

标签:style   blog   color   os   代码   c++   

原文地址:http://www.cnblogs.com/superzzh/p/3819704.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!