The Singleton pattern and its simplest implementation in Java

[2011-04-10] dev, java
(Ad, please don’t block)
This post motivates the Singleton design pattern and explains its implementation in Java.

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:
  • Enforce the constraint of exactly one instance.
  • Hint at how this class is to be used: To get an instance, one doesn’t invoke the constructor, but accesses the static variable. Thus, one cannot accidentally misuse the class. Classes with factory methods have private constructors for the same reason.
And now for the simplest way of implementing a Singleton in Java: as an enum.
    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:

  1. The classic book on design patterns, recommended: “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson, John M. Vlissides.
  2. The Wikipedia article on the Singleton pattern (which inspired this post and from which the enum implementation is taken).
  3. Google Guice, a lightweight dependency injection framework for Java. The website also explains dependency injection well.
  4. The Singleton pattern in JavaScript: not needed