附Code List 1:
#pragma once
class MsgDelegate
{
public:
virtual void Invoke(int msgID,int param1,int param2) =0;
protected:
MsgDelegate(int msgID):m_msgID(msgID) {}
virtual ~MsgDelegate(){}
int m_msgID;
};
class NonTypeDelegate : public MsgDelegate
{
public:
virtual void Invoke(int msgID,int param1,int param2)
{
if(msgID == m_msgID)
m_pfn(param1,param2);
}
NonTypeDelegate(int msgID,void (*pfn)(int,int)):MsgDelegate(msgID) { m_pfn = pfn; }
virtual ~NonTypeDelegate(){}
private:
void (*m_pfn)(int,int);
};
template <typename T>
class TypeDelegate : public MsgDelegate
{
public:
virtual void Invoke(int msgID,int param1,int param2)
{
if(msgID == m_msgID)
(m_pObj->*m_pfn)(param1,param2);
}
TypeDelegate(int msgID,T* pt, void (T::*pfn)(int,int)):MsgDelegate(msgID)
{
m_pObj = pt;
m_pfn = pfn;
}
~TypeDelegate(){}
private:
T *m_pObj;
void (T::*m_pfn)(int,int);
};
附CodeList2:
#include "stdafx.h"
#include ".\delegate.h"
#include <conio.h>
#include <list>
using namespace std;
int MSG_LVUP = 99;
class Player
{
public:
void LvUp(int param1,int param2)
{
printf("layer:vUp,%d,%d\n",param1,param2); }
};
class NetSession
{
private:
list<MsgDelegate*> m_delegateList;
public:
template<typename ObjType>
void Register(int msgID,ObjType *pObj,void (ObjType::*pfn)(int,int))
{
MsgDelegate *pD = new TypeDelegate<ObjType>(msgID,pObj,pfn);
m_delegateList.push_back(pD);
}
void TestRecvMsg()
{
for(list<MsgDelegate*>::iterator iter=m_delegateList.begin();
iter!=m_delegateList.end();++iter)
{
MsgDelegate *pD = (*iter);
pD->Invoke(MSG_LVUP,7,8);
pD->Invoke(MSG_LVUP+1,7,8);
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Player tmp;
NetSession ns;
ns.Register(MSG_LVUP,&tmp,Player:vUp); ns.TestRecvMsg();
_getch();
return 0;
}