singleton.h

00001 /*
00002 * "PS2" Application Framework
00003 *
00004 * University of Abertay Dundee
00005 * May be used for educational purposed only
00006 *
00007 * Author - Dr Henry S Fortuna
00008 *
00009 * $Revision: 1.3 $
00010 * $Date: 2007/10/01 18:08:26 $
00011 *
00012 */
00013 
00014 #ifndef __SINGLETON_H__
00015 #define __SINGLETON_H__
00016 
00017 #include <assert.h>
00018 
00019 // This class may seem a little strange if you have never seen a
00020 // singleton before. But it is a very useful, and increasingly
00021 // common data structure, particularly in games.
00022 
00023 // You can think of a singleton as a nice way to have a "global"
00024 // object, without the hassle of actually making the variable global
00025 // and then externing it all over the place.
00026 
00027 // If you derive your class from CSingleton, and then create a single
00028 // instance of the object in the source file, you can then access that
00029 // object from anywhere by calling the GetSingleton method of your class
00030 
00031 template <typename T> class CSingleton
00032 {
00033         // The one and only instance of this class
00034         static T * ms_Singleton;
00035 
00036 public:
00037         // Sets up the one and only instance
00038         CSingleton()
00039         {
00040                 assert(!ms_Singleton);
00041                 //int offset = (int)(T*)1 - (int)(CSingleton<T>*)(T*)1;
00042                 //ms_Singleton = (T*)((int)this + offset);
00043                 
00044                 // see http://www.codeproject.com/cpp/static_cast.asp
00045                 ms_Singleton = static_cast<T*>(this);
00046         }
00047 
00048         // Destroys the one and only instance
00049         ~CSingleton()
00050         {
00051                 assert(ms_Singleton);
00052                 ms_Singleton = 0;
00053         }
00054 
00055         // Returns the singleton
00056         static T& GetSingleton()
00057         {
00058                 assert(ms_Singleton);
00059                 return (*ms_Singleton);
00060         }
00061 
00062         // Returns a pointer to the singleton
00063         static T* GetSingletonPtr()
00064         {
00065                 return ms_Singleton;
00066         }
00067 };
00068 
00069 // This might look a bit confusing, but all it does is for each new singleton type that is created
00070 // it initialises it's static T * ms_Singleton member.
00071 template <typename T> T * CSingleton <T>::ms_Singleton = 0;
00072 
00073 #endif

Generated on Sun May 18 21:45:09 2008 for PS2X by  doxygen 1.5.4