一般来说通知框架可以有效的解耦业务逻辑,就类似于订阅者模式,任何模块都可以注册自己关注的接口,接口事件发生时会主动通知该模块。
通知框架向外部提供的宏:
//注册通知
#define LISTEN(INotify)\
AddInterface(#INotify, (void*)(INotify*)this);
//去除通知
#define UNLISTEN(INotify)\
RemoveInterface(#INotify, (void*)(INotify*)this);
//分发通知
#define NOTIFY(INotify, function)\
ActiveNotifyInstance(#INotify);\
for(int i=0; i< GetInterfaceCount(#INotify); ++i)\
{\
INotify* pInterface = (INotify*)(GetInterface(#INotify, i));\
if (nullptr != pInterface)\
{\
pInterface->function;\
}\
}\
接口实现:
// CoreCenter.cpp : 定义 DLL 应用程序的导出函数。
//
#include "CoreCenterDefine.h"
#include <map>
#include <vector>
#include <string>
typedef std::map<std::string, std::vector<void*> > TypeCoreMap;
namespace
{
TypeCoreMap _coreNotify;
}
void* GetInterface(const char* strNotify, int index)
{
return _coreNotify[strNotify][index];
}
int GetInterfaceCount(const char* strNotify)
{
auto iter = _coreNotify.find(strNotify);
if (iter != _coreNotify.end())
{
std::vector<void*>& vecInterfaces = iter->second;
return vecInterfaces.size();
}
return 0;
}
void AddInterface(const char* strNotify, void* pNotifyObject)
{
std::vector<void*>& vecInterfaces = _coreNotify[strNotify];
vecInterfaces.push_back(pNotifyObject);
}
void RemoveInterface(const char* strNotify, void* pNotifyObject)
{
if (_coreNotify.empty())
{
return;
}
auto iter = _coreNotify.find(strNotify);
if (iter != _coreNotify.end())
{
std::vector<void*>& vecNotifyObjects = iter->second;
std::vector<void*>::iterator iterObject = vecNotifyObjects.begin();
for (; iterObject != vecNotifyObjects.end(); ++iterObject)
{
if (*iterObject == pNotifyObject)
{
vecNotifyObjects.erase(iterObject);
break;
}
}
}
}