C++ 简单代理实现
来源:互联网 发布:html5 php 交互 编辑:程序博客网 时间:2024/06/11 12:47
OC中有一种常用的机制,delegate代理,或者委托,可以实现不同类之间的方法互相调用,调用者不需了解被调用者,被调用者也同样,只要被调用者实现了委托函数即可,这个机制可以实现很多功能。下面就是我在C++中进行的一次尝试,粗糙的模仿,只实现了基本功能,没有实现@required,@optional等限定符功能。
#include <string>#include <iostream>using namespace std;template <class classname>class Delegate{public://代理方法,需要被executor实现void doit(){cout << "requesting" << endl;if(_ex != NULL)_ex->doit();}void operator = (classname *ex){_ex = ex;}private:classname *_ex;};class Executor;class Caller{public:Delegate<Executor> myDelegate;};class Executor{private:string _name;public:Executor(string name):_name(name){}void doit(){cout <<_name << " :doing" <<endl;}};int main(){Caller *ca = new Caller();Executor *ex1 = new Executor("first executor");Executor *ex2 = new Executor("second executor");ca->myDelegate = ex1;ca->myDelegate.doit();ca->myDelegate = ex2;ca->myDelegate.doit();delete ex1,ex2;delete ca;system("pause");return 0;}其实,在真实需要代理的情况中,更接近于下面的形式,这样可以实现两个类互相调用,而避免循环引用。
#include <iostream>using namespace std;template <class classname>class Delegate{public://代理方法,需要被executor实现void doit(){cout << "requesting" << endl;if(_ex != NULL)_ex->doit();}void operator = (classname *ex){_ex = ex;}private:classname *_ex;};class Executor;class Caller{public:Delegate<Executor> myDelegate;void callDelegate(){myDelegate.doit();}};class Executor{public:Executor(){_ca = new Caller();}~Executor(){delete _ca;}void doit(){cout << "doing" <<endl;}void registerCaller(){_ca->myDelegate = this;}//仅为测试用void callMyself(){_ca->callDelegate();}private:Caller *_ca;};int main(){Executor *ex = new Executor();ex->registerCaller();ex->callMyself();delete ex;system("pause");return 0;}
- 简单实现Socks5代理(Python&C#)
- 动态代理--简单实现
- 动态代理--简单实现
- C++ 简单代理实现
- 动态代理简单实现
- OC简单实现代理
- swift 代理简单实现
- 实现简单的动态代理!
- 实现简单的动态代理!
- VC6实现简单代理服务
- Java动态代理简单实现
- 动态代理的简单实现
- iOS 简单代理(delegate)实现
- iOS 简单代理(delegate)实现
- Java NIO 实现简单代理
- iOS 简单代理(delegate)实现
- iOS 简单代理(delegate)实现
- 动态代理简单实现-1
- 无线网络基础知识
- HDU 3047 Zjnu Stadium (带权并查集)
- POJ1470
- 斐波那契查找
- hdu 3585 maximum shortest distance 二分小技巧
- C++ 简单代理实现
- js验证日期函数
- Fusion Charts Free 使用方法
- 若爱 就如桃花般地去爱
- 开源项目之Oracle驱动 OCILIB
- 修改vc6的目标文件输出路径
- Clear()
- 倒水问题
- UcosII 就绪表的理解