好久没有在csdn上写过东西了,这么多年,一方面是工作忙,下班到家也没有开过电脑了,要陪小孩玩;
下面分享一段代码,是用CPP做的一个简单的消息(协议)处理框架:
是通过成员函数指针+map来实现的:
关于成员函数指针与函数指针的区别,简单的说就是成员函数指针是指向类的成员函数,
而函数指针是用于指向普通的静态的函数;
上代码:
首先是一个基类:
#ifndef __BASEINTERFACE_H__
#define __BASEINTERFACE_H__
#include <iostream>
using namespace std;
class CBaseInterface;
typedef int (CBaseInterface::*MsgAction)(int, void *, int);
class CBaseInterface
{
public:
CBaseInterface(){};
virtual ~CBaseInterface(){};
};
#endif /* __BASEINTERFACE_H__ */
基类的作用是用于提供统一的接口,当然在这里主要是提供一个类的成员函数指针MsgAction
接下来就是处理框架类:
#ifndef __PROCESSDATA_H__
#define __PROCESSDATA_H__
#include <map>
#include "baseInterface.h"
using namespace std;
class CProcessData
{
protected:
CProcessData();
~CProcessData();
public:
static CProcessData* GetInstance();
int ProcessData(int iID, void *pData, int iDataLen); //处理消息
int RegIdFunction(int iID, MsgAction func); //注册消息处理成员函数
private:
map<int , MsgAction>m_FucnMap; //用于存储消息id与处理函数的对应表·
static CProcessData* m_pInstance;
};
类实现代码:
#include "processData.h"
CProcessData::CProcessData()
{
}
CProcessData::~CProcessData()
{
}
int CProcessData::RegIdFunction(int iID, MsgAction func)
{
m_FucnMap[iID] = func;
return 0;
}
int CProcessData::ProcessData(int iID, void *pData, int iDataLen)
{
map<int, MsgAction>::iterator iter = m_FucnMap.find(iID);
if ( iter != m_FucnMap.end() )
{
((CBaseInterface*)this->*(iter->second))(iID, pData, iDataLen);
}
else
{
cout<<"in CProcessData::ProcessData, not find id: "<<iID<<" process func!"<<endl;
}
return 0;
}
CProcessData* CProcessData::m_pInstance = NULL;
CProcessData* CProcessData::GetInstance()
{
if ( m_pInstance == NULL )
{
m_pInstance = new CProcessData;
}
return m_pInstance;
}
下面是测试用的类:
#include "baseInterface.h"
#include "processData.h"
class CTest: public CBaseInterface
{
public:
virtual ~CTest(){};
int Init()
{
CProcessData::GetInstance()->RegIdFunction(1, (MsgAction)&CTest::ProcessData1);
CProcessData::GetInstance()->RegIdFunction(2, (MsgAction)&CTest::ProcessData2);
return 0;
}
int ProcessData1(int iId, void *pData, int iLen)
{
val = 1;
cout <<" process cmd1, id: "<<iId<<", iLen: "<<iLen<<", val = "<<val++<<endl;
return 0;
}
int ProcessData2(int iId, void *pData, int iLen)
{
cout <<" process cmd1, id: "<<iId<<", iLen: "<<iLen<<", val = "<<val++<<endl;
return 0;
}
private:
int val;
};
下面是测试用的main函数:
#include <iostream>
#include "processData.h"
#include "test.h"
int main(int argc, char **argv)
{
CTest test;
test.Init();
CProcessData::GetInstance()->ProcessData(1, NULL, 2);
CProcessData::GetInstance()->ProcessData(2, NULL, 3);
return 0;
}
编译运行的结果:
源码下载地址:http://download.csdn.net/download/wuquan_1230/10136342
基于boost的框架分析:https://blog.csdn.net/wuquan_1230/article/details/79015656