The Singleton Pattern ensures a class has only one instance and provides a global point of access to it. It achieves this by requiring the class to manage a single instance of itself while preventing any outside classes from creating a new instance on their own.

Classic Singleton Implementation

public class Singleton{
    // The uniqueInstance class variable holds our one and only instance
    private static Singleton uniqueInstance;

    // Other useful instance variables here

    // The constructor is declared private; only Singleton can instantiate this class
    private Singleton(){}

    // Gives us a way to instantiate the class and return the instance
    public static Singleton getInstance(){
        if (uniqueInstance == null) {
            uniqueInstance = new Singleton();
        }
        return uniqueInstance;
    }

    // Other useful methods here
}

(Note: This basic implementation is not thread-safe and can create issues in multithreaded applications if not modified).

image.png

How It Works