Lesson 24 / 38
Singleton Pattern
Guarantee a class has exactly one instance and a single global access point, implement it safely with an enum, and know why it's often overused.
One instance, one access point
Singleton ensures a class has exactly one instance and provides a global point to reach it — useful for a shared config, connection pool, or cache. Overusing it turns the app into a web of hidden global state that's hard to test.
The safe way: an enum
A single-element enum is the simplest thread-safe singleton — the JVM guarantees exactly one instance is created, and it's serialization-safe for free.
enum AppConfig {
INSTANCE;
private final Properties props = load();
public String get(String key) { return props.getProperty(key); }
}
String url = AppConfig.INSTANCE.get("db.url");Prefer DI over a hand-rolled singleton
In a Spring app a @Bean or @Component is already a singleton by default (one instance per container) — no manual pattern needed, and it's swappable in tests. Reach for a hand-rolled singleton only outside a DI framework.