Intent
- Ensure that only one instance of a class is created.
- Provide a global point of access to the object.
Implementation
The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.
Singleton Example:
public class SingletonPattern{
private static SingletonPattern instance;
private SingletonPattern(){}
public static synchronized SingletonPattern getInstance(){
if (instance == null)
{
instance = new SingletonPattern();
}
return instance;
}
public static void main(String arg[]){
System.out.println("The output of two instance:");
SingletonPattern sp=new SingletonPattern();
System.out.println("First Instance: "+sp.getInstance());
sp=new SingletonPattern();
System.out.println("Second Instance:"+sp.getInstance());
}
}
Posted in: