Creational

Singleton

Singleton restricts a class to exactly one instance for its entire lifetime and gives every part of the program the same well-known way to reach that instance.

Complexity
Popularity

Problem

A logging module writes to one file on disk. If any part of the codebase can freely do `new Logger()`, nothing stops two different modules from opening independent file handles to the same log file - one write can silently clobber another, and buffered output can end up interleaved or lost.

What's needed is a guarantee, enforced by the class itself rather than by convention, that only one `Logger` will ever exist - plus a predictable way for distant, unrelated parts of the code to reach that one instance without threading a reference through every constructor and function signature between them.

Solution

Hide the constructor so nothing outside the class can call `new` on it directly, then add one static access method that the class itself controls. The first time that method runs, it builds the one permitted instance and stashes it in a static field; every call after that just hands back the same stashed reference instead of building anything new.

Because creation is funneled through a single method the class owns, the class can enforce "exactly one instance" as an invariant of its own code rather than relying on every caller to behave - and any part of the program can reach that instance by calling the same static method, with no reference-passing required.

When to Use

  • Reach for it when a resource is inherently singular - a hardware handle, a single log file, a connection pool - and more than one instance would cause real conflicts, not just redundancy.
  • Reach for it when many unrelated parts of the codebase need the same shared object and threading it through every layer as an explicit parameter would be impractical.

Real-World Examples

  • **Node.js module caching** - `require()`/`import` returns the same module instance on every import within a process, effectively making top-level module state a singleton.
  • **`java.lang.Runtime.getRuntime()`** - the JVM exposes exactly one Runtime object per process through a static access method, mirroring the classic Singleton shape.
  • **Redux/Vuex application store** - a single global store instance holds the entire application's state tree, and components reach it through one shared access point rather than creating their own copies.