创建扩展性良好的框架-单例框架(实现)

本文介绍了如何创建一个扩展性良好的单例框架。通过使用REGINSTANCE和REGNOTIFYINSTANCE宏来注册单例对象,使得对象能在不同模块间共享。REGNOTIFYINSTANCE宏在未使用单例时能自动创建,确保及时响应通知事件。GETINSTANCE函数则用于按接口获取单例实例,提升业务交互效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       单例可以算是业务开发中最常用的方式,一个对象可以全局使用,但是普通的单例对象只能在当前模块(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());
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值