AlgoViz

Singleton

medium 60 min

One object and one way to reach it.

Watch lesson4:52

Chapter mnemonic

Creational design patterns

Santa’s factory assembles blue penguins.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

One tower, one gate, one key. And better: hand out watches.

A village with one bell tower clock. Everybody looks up and sees the same time, two builders need one key, and whoever wants to play with the hands gets a toy clock.

Cheat sheet

Parts
static field, private constructor, static method
Race
check and build are two steps
Checked lock
check, lock, check, build, store
Java
enum, or holder if lazy
C++
static local, copy deleted
Python, TypeScript
a module
Go, Kotlin, .NET
sync.Once, object, Lazy
Unit
one per process, per loader
Failed static init
Java: never again
Live change
replace a snapshot
One job
lease with fencing number
Default
build in main, pass on

Spot it when you see

  • Settings, logger, pool, cache.
  • "Only one may exist."
  • "Write a thread safe singleton."
  • A static getInstance in a code review.
  • Tests that fail only together.

Tricks that stick

  • SINGLE: Static field, Instance control, No public constructor, Gate (getInstance), Lazy or eager, Ensure one.
  • A kingdom: one throne (one instance), guards at the gate (getInstance), nobody can crown themselves (private constructor), all bow to the same king (shared reference).
  • First check for speed, second check for truth.
  • Build, then show.
  • Ask: one per what?

Do not forget

  • No second check.
  • No volatile.
  • Storing before building.
  • User data inside.
  • A reset method for tests.
  • Believing in one across processes.
  • Opening connections in a static initializer.