GofPatterns Gofpatterns  





Design Patterns  «Prev 
Singleton: implementation

Java implementation of the Singleton Pattern

Here is a bare bones Singleton implemented in Java:
public class Singleton {
 static Singleton theInstance =  new Singleton();
 protected Singleton() { }
 public static Singleton getInstance() {
  return theInstance;
 }
}


The theInstance field is declared static.
This means its initializer (= new Singleton()) is executed the first time the class is loaded. A nonstatic field would be initialized when the constructor was invoked. You could make the field nonstatic by checking whether it had been initialized in getInstance and, if not, initializing it, but that's more trouble than it's worth since there's only a single instance in any case.
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 cannot get an instance of the class without invoking the method. Using a static method neatly solves this problem.