What is the Singleton Pattern, and when is it used?The singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits. To ensure that the user can create only one instance of this class, the following things have to be taken care of.
1. Make sure the user cannot explicitly create an instance of this object.
2. Provide access to this object from all areas of the application so that the need to create another instance never arises.
Uses:The Singleton class can be used in various places where one would need a common repository of information that can be accessed from all objects in an application. A common example could be Preferences for the user. The preferences can be loaded from a file into memory into a singleton class which all objects in the application can then access to get preferences information.
See also: http://www.javareference.com/jrexamples/viewexample.jsp?id=25Example:
public class Singleton{
private Singleton(){}
private static Singleton instance;
public static Singleton getInstance(){
if (instance == null)
instance = new Singleton();
return instance;
}