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