Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
Variants
Eager, holder, enum, static local, module: shorter and safer.
The point: writing the lock yourself is the exercise. In real code, pick the variant in which the language already locks.
Java
Eager, holder, enum
Java
final class Eager { private static final Eager INSTANCE = new Eager(); // when the class is initialized private Eager() {} static Eager getInstance() { return INSTANCE; }}final class Lazy { private Lazy() {} private static final class Holder { // initialized on first use static final Lazy INSTANCE = new Lazy(); } static Lazy getInstance() { return Holder.INSTANCE; }}enum Settings { INSTANCE; // made once by the runtime String databaseUrl() { return "db://main:5432"; }}All three rest on one promise of the Java language: a class is initialized once, under a lock that the runtime holds for that class. The inner class of the holder is not touched until getInstance names it, which makes it lazy.
Choosing in Java
| You need | Take | Why |
|---|---|---|
| It always runs | Eager | One line |
| It may never run, and it is costly | Holder | Lazy without a lock |
| It must survive serialization | Enum | Only the name is written, the constant is looked up |
| A parameter at creation time | None of them | Build it in main and pass it on |
Others
C++, Python, TypeScript
C++
class Settings { Settings() = default;public: Settings(const Settings&) = delete; Settings& operator=(const Settings&) = delete; static Settings& get() { static Settings instance; return instance; }};TypeScript
// config.tsexport const config = { apiUrl: "https://api.example.com", timeout: 5000 };// pool.tslet opening: Promise<Pool> | null = null;export function pool(): Promise<Pool> { return (opening ??= openPool()); // two callers, one promise}In Python a module does the same job: the Python FAQ calls a module the basis for implementing the singleton design pattern. A decorator is elegant on one page and surprising on the next, because the class name now means a function.
Which one?