singleton
DesignPatterns

Singleton Pattern

Singleton Pattern is a software design pattern that restricts the instance of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instance to a certain number of objects.

overview

The singleton design pattern solves these problems

  • How can it be ensured that a class has only one instance?
  • How can the sole instance of a class be accessed easily?
  • How can a class control its instantiation?
  • How can the number of instances of a class be restricted?

implementation

Singleton.java
public final class Singleton {
    // #1 private instance
    private static final Singleton INSTANCE = new Singleton();

    // #2 private constructor
    private Singleton() {}

    // #3 public method to get a Singleton instance
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

Reference