Skip to content

Singleton: One Shared Instance, and Why You Usually Want DI Instead

Learn how Singleton guarantees one instance with global access, why it is mostly an anti-pattern, and how dependency injection replaces it.

12 min readDesign patternCreational

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.

PriceBook is the single instance; CheckoutService depends only on the PriceSource interface, and the composition root or a test decides which implementation to pass in.PriceBook implements PriceSource. FakePriceBook implements PriceSource. CheckoutService has a PriceSource (injected). AppBootstrap calls PriceBook (getInstance()). AppBootstrap creates CheckoutService. CheckoutTest creates FakePriceBook. CheckoutTest creates CheckoutService.Privateconstructorone static instanceper process«interface»PriceSource+priceFor(sku): intPriceBook-instance (static),+getInstance()FakePriceBookflat price for testsAppBootstrapcomposition rootCheckoutService+total(cart): intCheckoutTestunit testinjectedgetInstance()
PriceBook is the single instance; CheckoutService depends only on the PriceSource interface, and the composition root or a test decides which implementation to pass in.

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`); // 300

When 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.

  1. 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.

  2. Make the constructor private (or, in Python, document that callers must use the accessor) so the rest of the code cannot create extra instances.

  3. Add a static field for the instance and a static getInstance() that creates it on first call and returns it thereafter.

  4. 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.

  5. Extract an interface with only the methods consumers need, and have the singleton implement it.

  6. Change consumers to take that interface through their constructors instead of calling getInstance() internally.

  7. 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.

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.