The Singleton Pattern Revisited - Tweaking the Singleton Class with Policies
(Page 4 of 5 )
Have you guessed how we can use the Singleton class for our case with the constructor that takes arguments? The question has already been answered; it can all be solved by implementing a specific singleton construction policy. We introduce a new creation policy!
Presume that a class takes an int and a char const * as arguments in the constructor; here is how we could implement our creation policy in the [Gamma] fashion:
template <class T> struct CreateClassXSingleton {
static T* Create() {
assert(NULL != m_strName);
return new T(m_nSize, m_strName);
}
static int m_nCount;
static char const *m_strName;
};
template <class T>
int CreateClassXSingleton<T>::m_nCount = 0;
template <class T> char const* CreateClassXSingleton<T>::m_strName = NULL;
The one thing you have to make sure of is that the static member variables of the creation policy class are set before you call Instance() on the singleton. That is why I put assert in there.
At the moment I am thinking about the possibilities of generalizing this further, but most solutions involve the need to make changes to the class we want to use as a singleton. Please feel free to drop me an email if you find a more generic solution.
Next: Singleton's Thread Safety >>
More C++ Articles
More By J. Nakamura