单例模式的C++ Template实现

  这是一个系列的文章,详情可点击关于这两年所经历项目的系列总结

在实现下一个游戏功能之前,我们先得实现一下单例模式,因为游戏中有很多地方会用到这样的功能,比如工具类等这些在游戏中只存一份的,需要用到单例模式。

这功能也无需多说,直接上代码,.h文件如下
#ifndef _SINGLETON_H_
#define _SINGLETON_H_

template<class T>
class  Singleton
{
private:
	static T * iInstance;
public:
	static T * getInstance();
	static void FreeInstance();
};

template<class T>
T * Singleton<T>::iInstance=0;

template<class T>
T * Singleton<T>::getInstance()
{
	if(iInstance == 0)
	{
		iInstance=new T();
	}

	return iInstance;
}

template<class T>
void Singleton<T>::FreeInstance()
{
	if(iInstance)
	{	
		delete iInstance;
		iInstance=0;
	}
}

#endif


关于如何使用该类,下一讲中就会用到。

猜你喜欢

转载自lizi07.iteye.com/blog/2104509