在实现下一个游戏功能之前,我们先得实现一下单例模式,因为游戏中有很多地方会用到这样的功能,比如工具类等这些在游戏中只存一份的,需要用到单例模式。
这功能也无需多说,直接上代码,.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
关于如何使用该类,下一讲中就会用到。