AlgoViz

Singleton

medium 60 min

One 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"; }}
Three variants without a lock of your own. The holder is also known as the Bill Pugh singleton.

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 needTakeWhy
It always runsEagerOne line
It may never run, and it is costlyHolderLazy without a lock
It must survive serializationEnumOnly the name is written, the constant is looked up
A parameter at creation timeNone of themBuild 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;    }};
A static local variable. If several threads arrive, the initialization happens once and the others wait.
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}
A module is run once. The object is the singleton, no class needed. For something that opens slowly, keep the 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?

Kotlin and Scala have a word for it: object. Go has sync.Once, and .NET has Lazy.