Skip to content
Velloreth
Programming 6 min read

The Singleton Pattern: Uses, Abuses, and Alternatives

Singleton guarantees one instance of a class. Learn how it works, why it is often criticised, and the better alternatives in modern code.

By

What the singleton is

The singleton pattern ensures a class has exactly one instance and provides a global point of access to it.

class Config {
  private static instance: Config | null = null;

  private constructor(public readonly apiUrl: string) {}

  static getInstance(): Config {
    if (!Config.instance) {
      Config.instance = new Config(process.env.API_URL!);
    }
    return Config.instance;
  }
}

const config = Config.getInstance();

Three elements define it:

  1. A private constructor, so nobody can create an instance directly.
  2. A static field holding the single instance.
  3. A static accessor that creates on first use and returns the same object thereafter.

The appeal is real. A singleton solves a genuine problem: some resources should exist once.

  • A configuration object should not be re-parsed per use.
  • A connection pool should not be recreated per request.
  • A logger should write to one destination.
  • A cache should be shared, not duplicated.

The singleton makes this easy. Any code that needs the resource calls getInstance() and gets the shared one, with no plumbing.

Why it is criticised

The criticism is not about the single instance. It is about the global access point.

Hidden dependencies

class OrderService {
  placeOrder(order: Order) {
    const config = Config.getInstance(); // hidden dependency
    const db = Database.getInstance();   // hidden dependency
    const logger = Logger.getInstance(); // hidden dependency
  }
}

Reading the constructor tells you nothing about what OrderService needs. The dependencies are buried in the method bodies. You cannot understand the class without reading every line.

Compare:

class OrderService {
  constructor(
    private config: Config,
    private db: Database,
    private logger: Logger,
  ) {}
}

The signature declares the dependencies. That is the whole difference, and it is significant.

Testing difficulty

A singleton cannot be replaced in tests. The class reaches for the global instance, so you cannot inject a fake.

// Test: how do you make Config return a test value?
const service = new OrderService();
service.placeOrder(order); // uses the real Config, real Database

You end up with workarounds: a reset() method for tests, a settable instance field, or environment variables that change behaviour. All of them are worse than injection.

Global mutable state

A singleton with mutable fields is global state. Any code can change it, and any code can be affected by the change.

class AppState {
  private static instance: AppState;
  currentUser: User | null = null; // global mutable state
}

This reintroduces every problem that global variables have: action at a distance, order-dependent behaviour, and bugs that are hard to reproduce.

Concurrency

In multi-threaded languages, lazy initialisation needs locking, and the lock is a bottleneck. Getting it wrong produces two instances, which defeats the purpose.

The modern alternatives

Module-level instance

Most languages have modules with a single instance per module. Exporting an object gives you a singleton without the class machinery.

// config.ts
export const config = {
  apiUrl: process.env.API_URL!,
  timeout: 5000,
};
// order-service.ts
import { config } from './config';

This is simpler, and it is testable if you use dependency injection at the boundaries. The module system guarantees one instance.

Dependency injection

Create the instance once at startup and pass it where needed.

// composition root
const config = loadConfig();
const db = new Database(config.databaseUrl);
const logger = new Logger(config.logLevel);

const orderService = new OrderService(config, db, logger);

The instance is still single — it is created once. But the dependency is explicit, and tests can pass a different one.

This is the recommended approach in most modern codebases. You get the single instance without the global access point.

A container

Dependency injection containers formalise this. You register a service as a singleton, and the container resolves it.

container.register('config', () => loadConfig(), { singleton: true });
container.register('db', (c) => new Database(c.config.databaseUrl), { singleton: true });

The container manages lifetimes, and consumers declare what they need. The single instance is a configuration detail rather than a design constraint.

When a singleton is defensible

There are cases where the single instance is a genuine constraint rather than a convenience.

A hardware device. There is one printer, one serial port, one GPU. Two instances would be wrong.

A connection pool. The pool exists to bound connections. Multiple pools defeat the purpose.

A process-wide cache. A cache that is not shared is not a cache.

Configuration loaded once. Re-parsing configuration per use is wasteful.

Even in these cases, the better pattern is to create the instance once and inject it. The singleton class is rarely necessary; the single instance is.

The distinction matters: “there should be one of these” is a lifetime decision, and dependency injection expresses it. “Everyone should be able to reach this from anywhere” is a coupling decision, and it is the part that causes problems.

The Java enum trick

In Java, the simplest thread-safe singleton is an enum:

public enum Config {
    INSTANCE;

    private final String apiUrl = System.getenv("API_URL");

    public String apiUrl() { return apiUrl; }
}

The JVM guarantees a single instance, initialisation is thread-safe, and serialisation is handled. It is the recommended approach when a singleton is genuinely needed in Java.

Common mistakes

Lazy initialisation without thread safety. Two threads can both see instance === null and create two objects.

Making everything a singleton. A singleton per service produces a web of global state that is impossible to test.

Using a singleton to avoid passing parameters. This is the real motivation in most cases, and it is a design smell. The parameter is being hidden, not eliminated.

Adding a reset() method for tests. This is a symptom. If tests need to reset global state, the state should not be global.

Assuming a singleton is one per application. In some runtimes, class loaders or module systems can produce more than one instance. The guarantee is weaker than it looks.

Practical guidance

  • Prefer dependency injection for anything that needs a single instance.
  • Use a module-level object when you want a simple shared value.
  • Reserve the singleton class for genuine constraints, and inject it anyway.
  • Never use a singleton for mutable application state.
  • Make dependencies explicit in constructors.
  • If you need a reset() for tests, the design is wrong.
  • Remember that “one instance” and “global access” are separate decisions — take the first, avoid the second.

For the related patterns, see design patterns for beginners and dependency injection without a framework. For the design principles behind the criticism, SOLID principles explained and pure functions and side effects.

Quotable summary

The singleton pattern ensures a class has exactly one instance and provides a global point of access to it. Its problems are not the single instance but the global access point: hidden dependencies, difficulty testing, and global mutable state, which is why it is often called an anti-pattern. In most cases a module-level object or dependency injection achieves the same single instance without the drawbacks, because the instance is created once at startup and passed explicitly. Singletons are defensible for genuinely global resources like configuration, connection pools, and hardware devices, and even then injection is preferable. The useful distinction is that “there should be one of these” is a lifetime decision, while “everyone can reach this from anywhere” is a coupling decision, and only the first is usually justified.

Frequently asked questions

What is the singleton pattern in simple terms?
A singleton is a class that allows only one instance to exist and gives everyone access to it. The first time you ask for it, it is created; every later request returns the same object.
Why is the singleton pattern considered bad?
Because it hides dependencies, makes testing hard, and introduces global mutable state. A class that reaches for a singleton cannot be tested in isolation, and the dependency is invisible in its signature.
What is the alternative to a singleton?
Dependency injection. Create the instance once at application startup and pass it to whatever needs it. The dependency becomes explicit, and tests can pass a fake.
Is a module-level object a singleton?
Effectively yes. A module that exports a single instance is a singleton without the class machinery. It is usually a better choice because it is simpler and does not prevent testing.
When is a singleton appropriate?
When the single instance is a genuine constraint, such as a hardware device, a connection pool, or a configuration object, and when it is injected rather than accessed globally. Even then, injection is usually preferable.
How do I make a singleton thread-safe?
Use lazy initialisation with a lock, or eager initialisation at class load. In languages with module-level state, the module system handles it. In Java, an enum is the simplest thread-safe singleton.