单例可以算是业务开发中最常用的方式,一个对象可以全局使用,但是普通的单例对象只能在当前模块(exe/dll)中使用,其他模块要使用的话需要显示导出才可以,不利于业务之间的交互。
宏接口:
//注册单例接口
#define REGINSTANCE(interface, CLASS)\
static auto interface##Func = []()\
{\
static CLASS object;\
return &object;\
};\
AddCreateInstanceFunc(#interface, interface##Func);
//通知拉活接口
#define REGNOTIFYINSTANCE(INotify, interface, CLASS)\
static auto interface##Func = []()\
{\
static CLASS object;\
return &object;\
};\
AddCreateInstanceFunc(#interface, interface##Func);\
AddNotifyInstance(#INotify, #interface);
REGINSTANCE注册单例对象,REGNOTIFYINSTANCE注册通知单例对象,后者与前者的区别在于后者可以未使用单例方法,也就是单例对象还未真正创建的时候,如果收到了通知会自动创建单例对象,然后接受通知事件。
GETINSTANCE根据接口获取单例对象
实现:
// CoreCenter.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include "CoreCenterDefine.h"
#include <map>
#include <vector>
#include <string>
typedef std::map<std::string, std::function<void*()> > TypeCreateObjectFuncMap;
typedef std::map<std::string, std::vector<std::string> > TypeNotifyInstanceMap;
namespace
{
TypeCreateObjectFuncMap _coreObjectFunc;
TypeNotifyInstanceMap _notifyInstance;
}
void* GetCoreInstance(const char* strInterface)
{
auto iter = _coreObjectFunc.find(strInterface);
if (iter != _coreObjectFunc.end())
{
return _coreObjectFunc[strInterface]();
}
return nullptr;
}
void AddCreateInstanceFunc(const char* strInterface, std::function<void*()> func)
{
_coreObjectFunc[strInterface] = func;
}
void AddNotifyInstance(const char* strNotify, const char* strInterface)
{
auto& vecFuncs = _notifyInstance[strInterface];
vecFuncs.push_back(strInterface);
}
void ActiveNotifyInstance(const char* strNotify)
{
auto iter = _notifyInstance.find(strNotify);
if (iter != _notifyInstance.end())
{
auto& vecInterfaces = iter->second;
for (auto& sinterface : vecInterfaces)
{
GetCoreInstance(sinterface.c_str());
}
}
}