核心方法:
typedef void*(*FUNC)();
#define GETINSTANCE(interface, object)\
{\
FUNC func = (FUNC)GetCreateObjectFunc(#interface);\
if(nullptr != func)\
{\
object = (interface*)func();\
}\
else\
{\
object = nullptr;\
}\
}
#define DEFINSTANCE(interface, CLASS)\
public:\
static interface* GetInstance()\
{\
static CLASS object; \
return &object;\
};
#define REGINSTANCE(interface, CLASS)\
AddCreateObjectFunc(#interface, (void*)(CLASS::##GetInstance));
测试代码:
#include <iostream>
#include <string>
class ICustomerNotify
{
public:
virtual void CustomerIn(std::string name) = 0;
virtual void CustomerOut(std::string name) = 0;
};
class CBook : public ICustomerNotify
{
public:
DEFINSTANCE(ICustomerNotify, CBook)
CBook()
{
LISTEN(ICustomerNotify);
}
~CBook()
{
UNLISTEN(ICustomerNotify);
};
void CustomerIn(std::string name)
{
std::cout << name << " has comming." << std::endl;
}
void CustomerOut(std::string name)
{
std::cout << name <<" has gone." << std::endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
REGINSTANCE(ICustomerNotify, CBook);
ICustomerNotify* pNotify = nullptr;
GETINSTANCE(ICustomerNotify, pNotify);
std::cout << pNotify << " ";
GETINSTANCE(ICustomerNotify, pNotify);
std::cout << pNotify << " ";
int a;
std::cin >> a;
}
执行结果: