一种单例的实现方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/linfengmove/article/details/82598586

核心方法:

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;
}

执行结果:

猜你喜欢

转载自blog.csdn.net/linfengmove/article/details/82598586