/ Published in: C++
URL: http://www.justinchouinard.com/2009/07/a-better-singleton-with-singleton-h/
Expand |
Embed | Plain Text
/** * \file Singleton.h * \brief The Singleton design pattern using templates. * \author Justin Chouinard <[email protected]> * *********************************************************************** * MyClass.h: *********************************************************************** * * class MyClass : public Singleton<MyClass> * { * .. * } * *********************************************************************** * MyClass.cc *********************************************************************** * * MyClass *Singleton<MyClass>::inst = 0; * *********************************************************************** * Others *********************************************************************** * Other files may access the instance by calling MyClass::getInstance(). * **/ #ifndef __SINGLETON_H__ #define __SINGLETON_H__ template <class Type> class Singleton { public: static Type *getInstance(void); private: static Type *inst; }; // end of class Singleton template <class Type> Type *Singleton<Type>::getInstance(void) { if (inst == 0) inst = new Type; return inst; } template <class Type> Type *Singleton<Type>::inst = 0; #endif // __SINGLETON_H__
You need to login to post a comment.
