GofPatterns GofPatterns

Singleton Pattern   «Prev 

C++ implementation of the Singleton

The C++ implementation is quite similar.
class Singleton {  
   static Singleton* theInstance;  
   static Singleton* getInstance(){
     if (theInstance == 0 ) {    
       theInstance = new Singleton();  
     return theInstance;

Singleton* Singleton::theInstance = 0;

The C++ implementation is very similar to the Java implementation. The major non-syntactic difference is that the C++ leaves initialization to the first invocation of getInstance(). This is because, in C++ static initializers are less reliable than in Java.
Most patterns need to shift and bend a little when translated into different languages. Indeed, the consequences and even motivation for a pattern can vary greatly between languages. Sometimes a pattern that's important in C++ is completely unneeded in Smalltalk or Java or vice versa.
The Singleton() constructor is declared protected so that subclasses can be created.
The constructor takes no arguments and does not actually do anything, so you might be inclined to leave it out. However, the default noargs constructor the compiler would insert is public.
The getInstance() method has to be static to avoid a chicken and an egg problem. If it were not static, you could not invoke it unless you had an instance of the class. But you can't get an instance of the class without invoking the method.
Using a static method neatly solves this problem.