单件(Singleton)模式的实现
熟悉设计模式的朋友一定知道著名的Singleton吧,如果不知道的话那就先去拜读一下GoF的大作吧,我在这里就不详细介绍了。
直接给大家共享出我们的实现方法,使用的是C++的template。
// singleton.h #ifndef _SINGLETON_H_ #define _SINGLETON_H_ template<class T> class Singleton { protected: Singleton() {} Singleton( const Singleton & ) {} Singleton &operator = (Singleton &) {} static T* pInst; public: static T* GetInstance() { if (pInst) return pInst; pInst = new T; return pInst; } static void ReleaseInstance() { if (pInst) { delete pInst; pInst = NULL; } } }; template<class T> T *Singleton<T>::pInst = 0; #endif
// suraid.h #ifndef _SURAID_H_ #define _SURAID_H_ #include "singleton.h" class Suraid : public Singleton<Texture> { public: Suraid(); }; #endif
// main.cpp #include "suraid.h" int main(void) { Suraid* suraid = Suraid::GetInstance(); return 0; }
代码应该很清晰了吧,这样实现的好处就是很方便,想使用单件的时候只要简单的继承一下就好了,但是也有一个缺点,通常我们理解的singleton都是不让实例化的,因为只能实例化一次,但是由于template的特性,构造函数无法申明成protected,也就导致可以实例化类,在使用的过程中要多加注意。