Posted By

jvc on 07/12/09


Tagged

patterns c design templates


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


Singleton


 / Published in: C++
 

URL: http://www.justinchouinard.com/2009/07/a-better-singleton-with-singleton-h/

  1. /**
  2.  * \file Singleton.h
  3.  * \brief The Singleton design pattern using templates.
  4.  * \author Justin Chouinard <[email protected]>
  5.  *
  6.  ***********************************************************************
  7.  * MyClass.h:
  8.  ***********************************************************************
  9.  *
  10.  * class MyClass : public Singleton<MyClass>
  11.  * {
  12.  * ..
  13.  * }
  14.  *
  15.  ***********************************************************************
  16.  * MyClass.cc
  17.  ***********************************************************************
  18.  *
  19.  * MyClass *Singleton<MyClass>::inst = 0;
  20.  *
  21.  ***********************************************************************
  22.  * Others
  23.  ***********************************************************************
  24.  * Other files may access the instance by calling MyClass::getInstance().
  25.  *
  26.  **/
  27.  
  28.  
  29. #ifndef __SINGLETON_H__
  30. #define __SINGLETON_H__
  31.  
  32. template <class Type>
  33. class Singleton
  34. {
  35. public:
  36. static Type *getInstance(void);
  37. private:
  38. static Type *inst;
  39. }; // end of class Singleton
  40.  
  41. template <class Type>
  42. Type *Singleton<Type>::getInstance(void)
  43. {
  44. if (inst == 0)
  45. inst = new Type;
  46.  
  47. return inst;
  48. }
  49.  
  50. template <class Type>
  51. Type *Singleton<Type>::inst = 0;
  52.  
  53. #endif // __SINGLETON_H__

Report this snippet  

You need to login to post a comment.