Mastering the Singleton Design Pattern in Java
Muneeb Javed
Software Engineer | Spring Boot | Java | MVC | OOP | C# | Android | Collection framework | Repository Pattern | SQL | Postgres |
Ensuring that a class has only one instance while providing a global access point is a common requirement in software development. The Singleton Design Pattern solves this by restricting object instantiation, making it ideal for logging, caching, configuration management, and database connections.
Why Use Singleton?
Popular Singleton Implementations in Java
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() { }
public static Singleton getInstance() { return INSTANCE; }
}
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}
领英推荐
public class Singleton {
private static Singleton instance;
private Singleton() { }
public static synchronized Singleton getInstance() {
if (instance == null) instance = new Singleton();
return instance;
}
}
public class Singleton {
private static volatile Singleton instance;
private Singleton() { }
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public enum Singleton {
INSTANCE;
public void show() { System.out.println("Singleton using Enum"); }
}
When to Use Singleton?
However, avoid Singleton if:
VP Backend Eng @ JPMorgan | Ex - Amazonian | Ex - Morgan Stanley | Ex- EPAM
3 周Helpful and simple to understand, worth looking into another pattern to achieve lazy singleton object with thread safety called "initialization on-demand holder pattern".