What is the Singleton pattern and how do you implement it correctly?

Topic: design-patterns, Creational Patterns. Level: Basic.

Answer

Singleton ensures a class has **exactly one instance** and provides a global access point to it — used for shared resources like configuration, logging, connection pools, or caches. The correct, thread-safe, lazy, reflection- and serialization-safe implementation in Java is an **enum** (Effective Java). If you need a class, use the **static holder idiom** (lazy + thread-safe without synchronization) or a double-checked-locking `volatile` field. Avoid naive lazy init (not thread-safe) and beware that singletons are effectively global state (hard to test/mock). ```java // Best: enum singleton — thread-safe, serialization/reflection-proof enum Config { INSTANCE; private final Properties props = load(); public String get(String k) { return props.getProperty(k); } private Properties load() { /* ... */ return new Properties(); } } // Usage: Config.INSTANCE.get("db.url"); // Alternative: lazy holder idiom (thread-safe, no locking) class Logger { private Logger() {} private static class Holder { static final Logger I = new Logger(); } public static Logger get() { return Holder.I; } } ```