home *** CD-ROM | disk | FTP | other *** search
/ AI Game Programming Wisdom / AIGameProgrammingWisdom.iso / SourceCode / 06 General Architectures / 06 Rabin / singleton.h < prev    next >
Encoding:
C/C++ Source or Header  |  2001-12-10  |  1.3 KB  |  45 lines

  1. /* Copyright (C) Steve Rabin, 2001. 
  2.  * All rights reserved worldwide.
  3.  *
  4.  * This software is provided "as is" without express or implied
  5.  * warranties. You may freely copy and compile this source into
  6.  * applications you distribute provided that the copyright text
  7.  * below is included in the resulting source code, for example:
  8.  * "Portions Copyright (C) Steve Rabin, 2001"
  9.  */
  10.  
  11. #ifndef __SINGLETON_H__
  12. #define __SINGLETON_H__
  13.  
  14. #include <assert.h>
  15.  
  16. //Singleton class as authored by Scott Bilas in the book Game Programming Gems
  17.  
  18. #define NULL 0
  19.  
  20. template <typename T>
  21. class Singleton
  22. {
  23. public:
  24.     Singleton( void )
  25.     {
  26.         assert( ms_Singleton == NULL );
  27.         int offset = (int)(T*)1 - (int)(Singleton <T> *)(T*)1;
  28.         ms_Singleton = (T*)((int)this + offset);
  29.     }
  30.     ~Singleton( void )  {  assert( ms_Singleton != NULL );  ms_Singleton = NULL;  }
  31.  
  32.     static T&   GetSingleton      ( void )  {  assert( ms_Singleton != NULL );  return ( *ms_Singleton );  }
  33.     static T*   GetSingletonPtr   ( void )  {  return ( ms_Singleton );  }
  34.     static bool DoesSingletonExist( void )  {  return ( ms_Singleton != NULL );  }
  35.  
  36. private:
  37.     static T* ms_Singleton;
  38.  
  39.     //SET_NO_COPYING( Singleton <T> );
  40. };
  41.  
  42. template <typename T> T* Singleton <T>::ms_Singleton = NULL;
  43.  
  44.  
  45. #endif    // __SINGLETON_H__