1 // ANNA - Anna is Not Nothingness Anymore //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
9 #ifndef anna_core_Singleton_hpp
10 #define anna_core_Singleton_hpp
14 #include <anna/core/mt/Mutex.hpp>
15 #include <anna/core/mt/Guard.hpp>
20 Singleton pattern. Limits the use to a unique class instance.
22 Default constructor for T must be private in order to avoid
23 external instantiation. Following, an example using class A:
26 On A class header file, we will have:
32 #include <anna/core/Singleton.hpp>
34 class A : public anna::Singleton <A> {
37 int getData () const { return a_data; }
40 void setOtherData (const ASD& otherData) { a_otherData = otherData; }
54 friend class functions::Singleton <A>;
67 void anyClass::anyFunction () throw (RuntimeException)
69 A& a (A::instantiate ());
71 cout << a.getData () << endl;
76 template <class T> class Singleton {
79 @return Class instance provided on template creation.
81 static T& instantiate() { return *alloc(true); }
84 Release the class instance provided in this template creation.
85 If no instance has been created, this will be ignored.
86 This method only have to be used during the program termination.
88 static void release() { alloc(false); }
91 static T* alloc(const bool allocate) {
93 static T* result(NULL);
95 if(allocate == true) {
97 Guard guard(mutex, "Singleton<T>::allocate");
104 Guard guard(mutex, "Singleton<T>::deallocate");