C++ 简单代理实现

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;
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值