一般來說通知框架可以有效的解耦業務邏輯,就類似於訂閱者模式,任何模塊都可以註冊自己關注的接口,接口事件發生時會主動通知該模塊。
通知框架向外部提供的宏:
//註冊通知
#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;
}
}
}
}