The Singleton is a design pattern [1] to ensure that a class has only a single instance. The name is derived from the mathematical term singleton which means a set with exactly one element. This pattern is mainly used if a class implements a service (which is usually instantiated only once). A typical Singleton looks as follows:
public class Singleton { public static final Singleton INSTANCE = new Singleton(); // Private constructor prevents external instantiation private Singleton() { } }Making the constructor private prevents code that is external to the class from instantiating it. This is done for two reasons:
public enum Singleton { INSTANCE; // Instance variables and methods go here }The enum automatically ensures that the Singleton cannot be instantiated externally, and the enum constant INSTANCE is a convenient way of creating the only instance.
As an alternative to the above solutions, one could also use static methods and store internal state in static variables. But then one loses some of the amenities of instances, such as the ability to conform to an interface. Or the ability to pass around a reference and invoke methods. It should be noted that the Singleton pattern hampers testability, because Singletons are harder to replace in a test environment. If you want to implement services (or components) via classes, it is better to use dependency injection (e.g. via Guice [3]). In addition to increased configurability, you also get explicit dependencies stated in constructors.
Related reading: