Ensure a class has exactly one instance in the process and provide a single access point to it. In modern code the useful half of that intent is "exactly one instance". The "global access" half is the part you usually replace with dependency injection.
Singleton is the pattern almost everyone can name, and the one interviewers most often use to test your judgement rather than your memory. Implementing it takes about ten lines. The harder part is explaining when it causes damage. This guide uses a single scenario throughout: a grocery delivery backend whose price book is expensive to load. You will see the classic implementation, the hidden coupling it introduces, and the alternative most teams end up with: create one instance at startup and pass it in. If you can explain both halves, you have the answer interviewers are looking for.
The problem
A situation where the obvious design starts to hurt.
Basketly is a grocery delivery startup. Its checkout service runs on 30 pods, and every pod needs the price book: about 180,000 SKUs parsed from the nightly catalog export. Parsing it takes roughly 4 seconds and uses around 300 MB of memory.
Over a year, four modules started needing prices: cart, promotions, invoicing and refunds. Each one called new PriceBook() on its own. A pod now parses the file four times at startup, holds four copies in memory, and readiness checks time out during deploys. Worse, the nightly refresh only updates the copy owned by the cart module, so for a few minutes each night invoicing charges yesterday's prices while the cart shows today's.
The team needs one price book per process that every module shares. The obvious fix is a Singleton. The less obvious question is how to get the sharing without having 40 classes reach into a global.
The solution
What the pattern proposes.
The classic Singleton makes the constructor private, keeps the one instance in a static field, and exposes a static getInstance() that creates the instance on first call and returns the same object afterwards. Basketly's PriceBook loads the export once, and every module that calls PriceBook.getInstance() gets the same object. That fixes memory, startup time and the stale copies.
The cost appears a month later. CheckoutService calls PriceBook.getInstance() inside its methods, so you cannot see from its constructor that it depends on prices. Unit tests cannot swap in a small fake, so every test loads the real export, and a test that mutates prices leaks into the next one. This is the global mutable state problem in a different form, and it is why Singleton is usually treated as an anti-pattern.
The better design keeps the one instance and removes the global lookups. Define a PriceSource interface. CheckoutService takes a PriceSource in its constructor. The application's bootstrap code, the composition root, is the only place that obtains the real PriceBook (via getInstance() or simply by constructing it once) and passes it down. Tests pass a FakePriceBook instead. You still get one instance per process, but it is now a decision made in one place rather than a hard-wired call scattered across the codebase. Many DI containers express exactly this as a singleton lifetime registration.
An everyday analogy
The same idea, outside software.
Think of the single master key for an apartment building held by the building manager. There should only ever be one, because duplicates cause chaos when the locks change. But tenants who need a repair do not walk into the manager's office and take the key off the hook themselves. The manager hands the key to the plumber who is booked for that job, and takes it back afterwards. If the plumber is a trainee practising on a mock-up door, they get a practice key instead. One key exists, but who uses it is decided by the person handing it out, not by everyone helping themselves.
Structure
The pieces and how they relate.
Participants
- PriceBook (Singleton)
- Holds the parsed catalog prices. Its constructor is private, the one instance lives in a static field, and getInstance() creates it lazily on first call and returns the same object afterwards.
- PriceSource (interface)
- The narrow contract consumers actually need: look up a price by SKU. It lets you substitute the singleton without touching consumers.
- CheckoutService (consumer)
- Computes cart totals. It receives a PriceSource through its constructor and never calls getInstance() itself, so its dependency is visible and replaceable.
- AppBootstrap (composition root)
- The single place that obtains the real PriceBook and wires it into every service. It is the only code that knows the instance is shared.
- FakePriceBook (test double)
- A trivial PriceSource used in unit tests, so tests run without loading the 180,000-SKU export and without sharing state between tests.
Pseudocode
The solution to the scenario, language-neutral.
interface PriceSource
method priceFor(sku) -> int
class PriceBook implements PriceSource
static field instance = null
field prices
private constructor(prices)
this.prices = prices
static method getInstance()
if instance is null
// in multi-threaded runtimes, guard this block with a lock
instance = new PriceBook(loadCatalogExport())
return instance
method priceFor(sku)
if sku not in prices: fail "Unknown SKU"
return prices[sku]
class CheckoutService
field prices: PriceSource
constructor(prices: PriceSource)
this.prices = prices
method total(cart)
sum = 0
for (sku, quantity) in cart
sum += prices.priceFor(sku) * quantity
return sum
// composition root: the only place that touches the singleton
book = PriceBook.getInstance()
checkout = new CheckoutService(book)
promotions = new PromotionService(book)
// unit test: no singleton involved
testCheckout = new CheckoutService(new FakePriceBook(flatPrice = 100))The code
The same solution in TypeScript, Python and PHP.
interface PriceSource {
priceFor(sku: string): number;
}
class PriceBook implements PriceSource {
private static instance: PriceBook | null = null;
static loads = 0;
private constructor(private readonly prices: ReadonlyMap<string, number>) {}
static getInstance(): PriceBook {
if (PriceBook.instance === null) {
PriceBook.instance = new PriceBook(PriceBook.loadPrices());
}
return PriceBook.instance;
}
private static loadPrices(): Map<string, number> {
PriceBook.loads += 1;
// Stands in for parsing the 180,000-SKU catalog export (prices in cents).
return new Map([
["milk-1l", 129],
["eggs-12", 349],
["bread-sourdough", 499],
]);
}
priceFor(sku: string): number {
const price = this.prices.get(sku);
if (price === undefined) {
throw new Error(`Unknown SKU: ${sku}`);
}
return price;
}
}
class FakePriceBook implements PriceSource {
constructor(private readonly flatPrice: number) {}
priceFor(_sku: string): number {
return this.flatPrice;
}
}
type CartLine = [sku: string, quantity: number];
class CheckoutService {
constructor(private readonly prices: PriceSource) {}
total(cart: CartLine[]): number {
return cart.reduce((sum, [sku, quantity]) => sum + this.prices.priceFor(sku) * quantity, 0);
}
}
// Composition root: the only place that touches the singleton.
const first = PriceBook.getInstance();
const second = PriceBook.getInstance();
console.log(`same instance: ${first === second ? "yes" : "no"}, loads: ${PriceBook.loads}`);
const cart: CartLine[] = [
["milk-1l", 2],
["eggs-12", 1],
];
const checkout = new CheckoutService(PriceBook.getInstance());
console.log(`total: ${checkout.total(cart)} cents`); // 607
// Unit test style: inject a fake, no catalog load, no shared state.
const testCheckout = new CheckoutService(new FakePriceBook(100));
console.log(`test total: ${testCheckout.total(cart)} cents`); // 300import threading
from typing import Optional, Protocol
class PriceSource(Protocol):
def price_for(self, sku: str) -> int: ...
class PriceBook:
"""Use PriceBook.get_instance(); do not call the constructor directly."""
_instance: Optional["PriceBook"] = None
_lock = threading.Lock()
loads = 0
def __init__(self, prices: dict[str, int]) -> None:
self._prices = prices
@classmethod
def get_instance(cls) -> "PriceBook":
if cls._instance is None:
with cls._lock:
if cls._instance is None: # double check inside the lock
cls._instance = cls(cls._load_prices())
return cls._instance
@classmethod
def _load_prices(cls) -> dict[str, int]:
cls.loads += 1
# Stands in for parsing the 180,000-SKU catalog export (prices in cents).
return {"milk-1l": 129, "eggs-12": 349, "bread-sourdough": 499}
def price_for(self, sku: str) -> int:
try:
return self._prices[sku]
except KeyError:
raise KeyError(f"Unknown SKU: {sku}") from None
class FakePriceBook:
def __init__(self, flat_price: int) -> None:
self._flat_price = flat_price
def price_for(self, sku: str) -> int:
return self._flat_price
class CheckoutService:
def __init__(self, prices: PriceSource) -> None:
self._prices = prices
def total(self, cart: list[tuple[str, int]]) -> int:
return sum(self._prices.price_for(sku) * quantity for sku, quantity in cart)
if __name__ == "__main__":
# Composition root: the only place that touches the singleton.
first = PriceBook.get_instance()
second = PriceBook.get_instance()
same = "yes" if first is second else "no"
print(f"same instance: {same}, loads: {PriceBook.loads}")
cart = [("milk-1l", 2), ("eggs-12", 1)]
checkout = CheckoutService(PriceBook.get_instance())
print(f"total: {checkout.total(cart)} cents") # 607
# Unit test style: inject a fake, no catalog load, no shared state.
test_checkout = CheckoutService(FakePriceBook(100))
print(f"test total: {test_checkout.total(cart)} cents") # 300<?php
declare(strict_types=1);
interface PriceSource
{
public function priceFor(string $sku): int;
}
final class PriceBook implements PriceSource
{
private static ?PriceBook $instance = null;
public static int $loads = 0;
/** @param array<string, int> $prices */
private function __construct(private readonly array $prices)
{
}
public static function getInstance(): PriceBook
{
if (self::$instance === null) {
self::$instance = new PriceBook(self::loadPrices());
}
return self::$instance;
}
/** @return array<string, int> */
private static function loadPrices(): array
{
self::$loads++;
// Stands in for parsing the 180,000-SKU catalog export (prices in cents).
return ['milk-1l' => 129, 'eggs-12' => 349, 'bread-sourdough' => 499];
}
public function priceFor(string $sku): int
{
if (!array_key_exists($sku, $this->prices)) {
throw new InvalidArgumentException("Unknown SKU: {$sku}");
}
return $this->prices[$sku];
}
private function __clone()
{
}
public function __wakeup(): void
{
throw new LogicException('Cannot unserialize a singleton');
}
}
final class FakePriceBook implements PriceSource
{
public function __construct(private readonly int $flatPrice)
{
}
public function priceFor(string $sku): int
{
return $this->flatPrice;
}
}
final class CheckoutService
{
public function __construct(private readonly PriceSource $prices)
{
}
/** @param list<array{0: string, 1: int}> $cart */
public function total(array $cart): int
{
$sum = 0;
foreach ($cart as [$sku, $quantity]) {
$sum += $this->prices->priceFor($sku) * $quantity;
}
return $sum;
}
}
// Composition root: the only place that touches the singleton.
$first = PriceBook::getInstance();
$second = PriceBook::getInstance();
$same = $first === $second ? 'yes' : 'no';
echo "same instance: {$same}, loads: " . PriceBook::$loads . PHP_EOL;
$cart = [['milk-1l', 2], ['eggs-12', 1]];
$checkout = new CheckoutService(PriceBook::getInstance());
echo 'total: ' . $checkout->total($cart) . ' cents' . PHP_EOL; // 607
// Unit test style: inject a fake, no catalog load, no shared state.
$testCheckout = new CheckoutService(new FakePriceBook(100));
echo 'test total: ' . $testCheckout->total($cart) . ' cents' . PHP_EOL; // 300When to use it
Situations where it pays off.
A resource must exist exactly once per process because duplicates are wrong or wasteful, such as a large in-memory catalog, a connection pool or a hardware handle.
Two copies would waste memory or disagree with each other. Basketly's four price books drifted out of sync after the nightly refresh.
The object is effectively immutable after creation, or its state is deliberately process-wide, like a logger configured once at startup.
Read-only shared state carries little of Singleton's risk. The trouble comes from shared mutable state that tests and modules can change behind each other's backs.
You work in a codebase with no DI container and need a quick, contained way to share one instance.
A Singleton accessed only from the composition root gives you the uniqueness without spreading global lookups through business code.
Avoid it when the only motivation is convenience, so that any class can grab the object without it being passed in.
That is a global variable with a class wrapper. It hides dependencies, couples every caller to a concrete class, and makes parallel or isolated tests painful.
How to implement it
Steps to introduce it in existing code.
Confirm you really need exactly one instance. If you just need to share one, creating it once at startup and passing it around is enough, and no pattern is required.
Make the constructor private (or, in Python, document that callers must use the accessor) so the rest of the code cannot create extra instances.
Add a static field for the instance and a static
getInstance()that creates it on first call and returns it thereafter.In multi-threaded runtimes, make creation thread-safe: a lock with a double check, eager initialisation, or a language feature such as a module-level object or lazy static.
Extract an interface with only the methods consumers need, and have the singleton implement it.
Change consumers to take that interface through their constructors instead of calling
getInstance()internally.Call
getInstance()in one place, the composition root, and pass the result down. In tests, pass a fake instead.
Pros and cons
What you gain and what you pay.
Pros
- Guarantees a single instance, which prevents duplicated memory and diverging copies of shared data.
- Lazy initialisation means the expensive load only happens if and when the object is first needed.
- Simple to implement and to recognise; any reviewer knows what
getInstance()means. - Combined with an interface and constructor injection, you keep the uniqueness while losing most of the downsides.
Cons
- Calling
getInstance()from inside business code hides dependencies; a class's constructor no longer tells you what it needs. - Shared state survives between unit tests, causing order-dependent failures, and swapping in a fake requires hacks such as reset methods.
- Callers depend on a concrete class, which violates dependency inversion and makes later changes ripple through the codebase.
- Lazy creation needs careful synchronisation in multi-threaded runtimes, and "one per process" breaks down across multiple processes, pods or class loaders.
- It mixes two responsibilities in one class: its real job and controlling its own lifecycle.
Relations with other guides
Patterns it's often confused or combined with.
- Global Mutable State
A Singleton with mutable fields is global mutable state behind a method call. The fixes for that smell, passing the dependency explicitly and narrowing what can change, are the same ones that tame a Singleton.
- Abstract Factory: Create Families of Objects That Belong Together
Concrete factories usually need only one instance per configuration, so they are often implemented as singletons or registered with a singleton lifetime in a DI container.
- Facade Pattern: One Simple Entry Point to a Messy Subsystem
A facade over a subsystem is often needed just once per application. Make it a single instance created in the composition root rather than a global accessor.
- Flyweight Pattern: Share Immutable State Across Many Objects
Flyweight shares many small immutable instances keyed by their intrinsic state, while Singleton allows exactly one instance of a class. A flyweight factory itself is often a single shared instance.
- Builder Pattern: Assemble Complex Objects Step by Step
Builder can assemble a complex shared object step by step at startup; the composition root then holds the single result instead of the object controlling its own creation.
- Inappropriate Intimacy: Classes That Know Too Much About Each Other
When many classes reach into one global instance and poke at its internals, the coupling grows unnoticed. Injecting a narrow interface keeps that intimacy in check.
Common questions
Short answers to the usual doubts.
Why do people call Singleton an anti-pattern if it is in the original GoF book?
The single-instance guarantee is fine. The problem is the global access point. When any class can call getInstance(), dependencies become invisible, callers are tied to one concrete class, and state leaks between tests. Most of the criticism targets that habit, not the idea of having one instance. Keep the one instance, inject it, and the criticism mostly goes away.
What should I say in an interview when asked to implement a Singleton?
Write the private constructor, static field and lazy accessor, then mention thread safety for your language. After that, say how you would actually use it: behind an interface, obtained only in the composition root and passed in through constructors, or registered with a singleton lifetime in a DI container. That shows you know the mechanics and the trade-offs.
Is a Singleton thread-safe?
Not automatically. If two threads call a naive getInstance() at the same time, both can see a null instance and create two objects. Fixes include eager initialisation, a lock with a double check as in the Python sample, or language features that guarantee one-time initialisation. Node.js runs your JavaScript on one thread, and PHP builds a fresh process state per request, so the race does not arise there in the same way.
Does a Singleton give me one instance across my whole system?
No. It gives one instance per process, or per class loader or module registry. Basketly's 30 pods each have their own PriceBook. In PHP the instance lives only for one request. If you need one coordinator across machines, you need a distributed mechanism such as a lock or leader election, not a Singleton.
How do I test code that already calls getInstance() everywhere?
Refactor gradually. Extract an interface for what callers use, add a constructor parameter of that type that defaults to getInstance(), and update tests to pass a fake. Once every caller receives the dependency, remove the defaults and move the single getInstance() call to the composition root. Avoid adding a public reset method just for tests; it lets production code reset the instance too.
Are module-level objects in Python or exported instances in JavaScript singletons?
Effectively, yes. A module is loaded once and cached, so an object created at module level is shared by every importer. That is often the most idiomatic way to get one instance in those languages, but it has the same downside: importing it directly from business code hides the dependency. Pass it in where testability matters.