A reader wrote in some time after we ran a short series on the Singleton pattern with some questions. These included how to construct a singleton when the class has a non-trivial constructor with arguments that are calculated at run-time, and how to use the singleton in a multi-threaded environment. If you were wondering about these issues as well, keep reading.
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:
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.