2
Copyright (C) 2004 Erik Hjortsberg
4
Taken from the file OgreSingleton.h from the Ogre project, release 0.14
7
This program is free software; you can redistribute it and/or modify
8
it under the terms of the GNU General Public License as published by
9
the Free Software Foundation; either version 2 of the License, or
10
(at your option) any later version.
12
This program is distributed in the hope that it will be useful,
13
but WITHOUT ANY WARRANTY; without even the implied warranty of
14
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
GNU General Public License for more details.
17
You should have received a copy of the GNU General Public License
18
along with this program; if not, write to the Free Software
19
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22
#ifndef _EMBER_SINGLETON_H__
23
#define _EMBER_SINGLETON_H__
30
@brief Template class for creating single-instance global classes.
32
Whenever you need a singleton in the system you should inherit from this, such as
34
class Foo : public Ember::Singleton<Foo>
37
In your implementation you're then required to intialize ms_Singleton to 0, such as this
39
template<> Ember::Foo* Ember::Singleton<Ember::Foo>::ms_Singleton = 0;
42
Whenever you need the singleton instance in your project you can then get it by calling @see getSingleton() or @see getSingletonPtr()
43
Note that you still have to provide lifetime service and ownership and need to both create and destroy the instance where appropriate.
45
template <typename T> class Singleton
50
@brief The static variable holding the singleton instance.
51
Remember to instanciate this to 0 in your implementation.
53
static T* ms_Singleton;
58
* @brief Standard constructor.
62
assert( !ms_Singleton );
63
ms_Singleton = static_cast< T* >( this );
68
assert( ms_Singleton ); ms_Singleton = 0;
72
* @brief Gets the singleton instance.
73
* @return The singleton instance.
75
static T& getSingleton( void )
77
assert( ms_Singleton );
78
return ( *ms_Singleton );
82
* @brief Gets a pointer to the singleton instance.
83
* @return A pointer to the singleton instance.
85
static T* getSingletonPtr( void )
87
assert( ms_Singleton );
92
* @brief Gets the singleton instance.
93
* @return The singleton instance.
95
static T& instance( void )
97
return getSingleton();
101
* @brief Returns true if there's a singleton registered with the system.
102
* @return True if there's a singleton available.
104
static bool hasInstance()
106
return ms_Singleton != 0;