Design Patterns: Singleton
A Creational Design Pattern
The Singleton design pattern is one of the Creational patterns and deals with the problem of restricting the creation of objects of a class to a single instance.
Here is the basic formulation of the Singleton design pattern:
public class Singleton
{
private static Singleton theInstance = new Singleton();
//Other fields
//Note the private constructor
private Singleton()
{
//Initialize instance fields
}
public static Singleton getInstance()
{
return theInstance;
}
//Other public methods
}
An alternate form of this definition that performs lazy initialization of the class instance looks like this:
public class Singleton
{
private static Singleton theInstance
//Other fields
//Note the private constructor
private Singleton()
{
//Initialize instance fields
}
public static Singleton getInstance()
{
if (theInstance == null)
theInstance = new Singleton();
return theInstance;
}
//Other public methods
}