-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSingleton.h
60 lines (51 loc) · 1.15 KB
/
Singleton.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#ifndef SINGLETON_H
#define SINGLETON_H
/**
* An implementation of the Singleton design pattern. This allows us to use global instances of certain classes.
*
* \tparam T the class to encapsulate.
*/
template <class T>
class Singleton
{
public:
/**
* Create a new instance of a class.
*
* \note this only works for classes that have constructors without parameters.
*/
/**
* Destroy the encapsulated instance of the class.
*/
static void DestroyInstance()
{
delete instance;
}
/**
* Get the encapsulated instance of the class. If one has not been created already, it will be done here.
*
* \return the encapsulated instance of the class.
*/
static T& GetInstance()
{
return *instance;
}
/**
* Set the instance of the class. This is useful when classes must be constructed manually.
*
* \param newInstance the user-created instance of the class to be used.
*/
static void SetInstance(T* newInstance)
{
if( instance )
DestroyInstance();
instance = newInstance;
}
private:
Singleton() { }
~Singleton() { }
static T* instance;
};
template <class T>
T* Singleton<T>::instance = 0;
#endif // SINGLETON_H