The Singleton pattern guarantees that a class has only one instance for the entire lifetime of the application, and provides one global access point to it.
Tip: reach for Singleton when you need exactly one shared object — like a configuration manager, a connection pool, or a logger — and creating multiple instances would cause bugs or waste resources.
The structure
The Singleton class exposes one static access point; every caller receives a reference to the same instance.
The class keeps a reference to its own single instance in a private static field, hides its constructor so nobody else can create new instances directly, and exposes one public static method that hands out that shared instance.
Implementing it in Java
public class Singleton {
private static Singleton instance;
// Private constructor — nothing outside this class can call `new Singleton()`
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
Singleton a = Singleton.getInstance();
Singleton b = Singleton.getInstance();
System.out.println(a == b); // true — both variables point to the exact same object
A word of caution
The basic version above isn’t thread-safe — two threads calling getInstance() at the same time could both see instance == null and create two separate objects. Production code typically guards against this with synchronization or by initializing the instance eagerly. We’ll cover thread-safe variations in a later lesson.
What’s next
Next up: the Factory pattern, another creational pattern that solves a different problem — delegating which class gets instantiated, rather than how many instances exist.