Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
Five ways to one instance, and one way around it
Read it, run it, change a line and run it again.
Loading editor…
Complete and runnable. The other tabs show the usual forms of each language: checked lock, eager, holder and enum in Java, static local, atomic and call_once in C++, class, closure, registry and promise in TypeScript.
The same in Java
// 1. Double-checked locking. volatile is not optional.final class Checked { private static volatile Checked instance; private Checked() {} static Checked getInstance() { if (instance == null) { // first check, no lock synchronized (Checked.class) { if (instance == null) { // second check, with the lock instance = new Checked(); } } } return instance; }}// 2. Eager. The class loader does the work. Simple and safe.final class Eager { private static final Eager INSTANCE = new Eager(); private Eager() {} static Eager getInstance() { return INSTANCE; }}// 3. Holder (also called Bill Pugh singleton). Lazy, no lock of our own.final class Holder { private Holder() {} private static final class Box { static final Holder INSTANCE = new Holder(); } static Holder getInstance() { return Box.INSTANCE; }}// 4. Enum. Also closed against reflection and serialization.enum Database { INSTANCE; private final java.util.List<String> log = new java.util.concurrent.CopyOnWriteArrayList<>(); void query(String sql) { log.add(sql); } int count() { return log.size(); }}final class Main { public static void main(String[] args) { System.out.println(Checked.getInstance() == Checked.getInstance()); System.out.println(Eager.getInstance() == Eager.getInstance()); System.out.println(Holder.getInstance() == Holder.getInstance()); Database.INSTANCE.query("select 1"); System.out.println(Database.INSTANCE.count()); }}The same in C++
#include <atomic>#include <iostream>#include <memory>#include <mutex>// 1. Meyers singleton: a static local. Thread safe since C++11. Use this one.class Meyers { Meyers() = default;public: Meyers(const Meyers&) = delete; Meyers& operator=(const Meyers&) = delete; static Meyers& getInstance() { static Meyers instance; return instance; }};// 2. Double-checked locking. The pointer must be atomic, or it is a data race.class Checked { static inline std::atomic<Checked*> instance{nullptr}; static inline std::mutex lock; Checked() = default;public: Checked(const Checked&) = delete; Checked& operator=(const Checked&) = delete; static Checked& getInstance() { Checked* seen = instance.load(std::memory_order_acquire); if (!seen) { std::lock_guard<std::mutex> hold(lock); seen = instance.load(std::memory_order_relaxed); if (!seen) { seen = new Checked(); // never deleted, on purpose instance.store(seen, std::memory_order_release); } } return *seen; }};// 3. call_once with a smart pointer: destroyed at exit.class Once { static inline std::unique_ptr<Once> instance; static inline std::once_flag flag; Once() = default;public: Once(const Once&) = delete; Once& operator=(const Once&) = delete; static Once& getInstance() { std::call_once(flag, [] { instance.reset(new Once()); }); return *instance; }};int main() { std::cout << std::boolalpha << (&Meyers::getInstance() == &Meyers::getInstance()) << "\n" << (&Checked::getInstance() == &Checked::getInstance()) << "\n" << (&Once::getInstance() == &Once::getInstance()) << "\n";}The same in TypeScript
// 1. Classic: a private constructor and a static field.class Classic { private static instance: Classic | null = null; readonly madeAt = new Date(); private constructor() {} static getInstance(): Classic { return (Classic.instance ??= new Classic()); }}// 2. A closure: the variable is private because nothing exports it.const logger = (() => { let instance: { logs: string[]; log(message: string): void } | null = null; return { getInstance() { return (instance ??= { logs: [], log(message: string) { this.logs.push(message); }, }); }, };})();// 3. A module. The shortest one: in config.ts write// export const config = { apiUrl: "https://api.example.com", timeout: 5000 };// Every import of the same file gets the same object.// 4. A registry of named instances.class Registry { private readonly made = new Map<string, unknown>(); get<T>(key: string, create: () => T): T { if (!this.made.has(key)) this.made.set(key, create()); return this.made.get(key) as T; }}// 5. An async resource: keep the promise, not the result.class Connection { private static opening: Promise<Connection> | null = null; static get(): Promise<Connection> { return (Connection.opening ??= Connection.open().catch((error) => { Connection.opening = null; // the next caller may try again throw error; })); } private static async open() { return new Connection(); }}console.log(Classic.getInstance() === Classic.getInstance());logger.getInstance().log("hello");logger.getInstance().log("world");console.log(logger.getInstance().logs.length); // 2const registry = new Registry();const db = registry.get("database", () => ({ connected: true }));console.log(db === registry.get("database", () => ({ connected: false })));Promise.all([Connection.get(), Connection.get()]).then(([a, b]) => console.log(a === b));export {};