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 - Policy-based Class Design (Page 3 of 5 )
In brief, policy-based class design is used to assemble a class out of little classes (called policies), each of which takes care of only one behavioral or structural aspect. If you use the Standard Template Library, you are probably already familiar with std::string. This is a typedef for the std::basic_string class which accepts char_traits as one of its template parameters. Policies are very much like traits, with the main difference being that they focus on behavior rather than type.
With the Singleton class, the creation process of the object that has to become the singleton has been extrapolated into policy classes. The reason for this is that there might be different reasons to construct the object in different ways.
Because you can mix and match policies, you can achieve a combinatorial set of behaviors by using only a small core of elementary components. The downside of this is that what used to be declared and defined in a single class is now scattered over multiple declarations and definitions.
For someone looking at that code for the first time, it can become a bit hard to understand what is going on (especially if that someone hasn’t seen or used policies before). On the other hand, I won’t claim that writing the same class over and over again while only tweaking the pieces that could go into a policy is a better solution. If you write your code like that it won’t be more intelligible -- worse, it will be a lot more sensitive to bugs! (Not to mention the fact that changing and fixing the code becomes tedious, since you will have to make changes to a lot of classes, when you could have handled it with just the class and a couple of policies.)
You can see in the singleton code that there are two policies given for the creation of an object inside the singleton class (CreateLeaking and CreateMeyers). When you declare the Singleton you provide the creation policy you like as a template parameter (e.g. typedef Singleton<MyClass, CreateLeaking> MySingleton). Next when Singleton::Instance() is called, it uses the Create function stored in that policy (i.e. CreationPolicy<T>::Create()). So in the CreateLeaking case we end up executing: