Singleton

Make sure a class has exactly one instance and give the whole program one way to reach it. Useful, and the most overused pattern.

Description

A singleton hides its constructor and exposes a static accessor, AppConfig.get(), that creates the instance on first use and returns the same one forever after. Typical candidates: configuration, a logger, a connection pool, a cache.

It solves a real problem, one shared resource, but it is also global state with a nicer name. Code that calls AppConfig.get() deep inside hides a dependency and is harder to test. In TypeScript, an exported module-level instance gives you the same "one instance" guarantee with less ceremony, and dependency injection keeps the dependency visible.

Class diagram

get()get()AppConfig- static instance: AppConfig+ apiUrl: string+ region: string- constructor(env)+ static get(): AppConfig+ static resetForTests()ApiClient+ url(path): stringStorageBucket+ name(): string

Singleton pattern class diagram

  1. Class AppConfig with - constructor(env), + static get(): AppConfig, + static resetForTests().
  2. Class ApiClient with + url(path): string.
  3. Class StorageBucket with + name(): string.
  4. ApiClient get() AppConfig.
  5. StorageBucket get() AppConfig.

Sequence diagram

ApiClientAppConfigStorageBucketopt[no instance yet]1. get()2. new AppConfig(env)3. instance4. get()5. same instance

Singleton pattern sequence diagram

  1. ApiClient → AppConfig: get().
  2. AppConfig → AppConfig: new AppConfig(env).
  3. ApiClient receives "instance" back from AppConfig.
  4. StorageBucket → AppConfig: get().
  5. StorageBucket receives "same instance" back from AppConfig.

TypeScript example

A configuration singleton with a private constructor. Two unrelated classes share one instance, loaded once. The reset hook exists because tests need it, which is itself a hint to prefer injection.

singleton.ts
// Singleton: one shared configuration object, loaded once, used everywhere.

type Env = Record<string, string | undefined>;
const processEnv: Env = { API_URL: "https://api.example.com", REGION: "eu-north-1" };

class AppConfig {
  private static instance: AppConfig | undefined;
  static loads = 0;

  readonly apiUrl: string;
  readonly region: string;

  // private: nobody outside can call `new AppConfig()`
  private constructor(env: Env) {
    AppConfig.loads += 1;
    this.apiUrl = env.API_URL ?? "http://localhost:3000";
    this.region = env.REGION ?? "local";
  }

  static get(): AppConfig {
    AppConfig.instance ??= new AppConfig(processEnv);
    return AppConfig.instance;
  }

  /** For tests only: forget the instance so the next get() reloads. */
  static resetForTests(): void {
    AppConfig.instance = undefined;
  }
}

// Two unrelated parts of the app read the same instance.
class ApiClient {
  url(path: string): string {
    return `${AppConfig.get().apiUrl}${path}`;
  }
}

class StorageBucket {
  name(): string {
    return `uploads-${AppConfig.get().region}`;
  }
}

export function demo(): string[] {
  const api = new ApiClient();
  const bucket = new StorageBucket();
  return [
    api.url("/orders"),
    bucket.name(),
    `same instance: ${AppConfig.get() === AppConfig.get()}`,
    `config loaded ${AppConfig.loads} time(s)`,
  ];
}

When to use it

Use it when

  • There must be exactly one of something for correctness: one connection pool, one in-process cache, one metrics registry.
  • Creating the object is expensive and it's safe to share.
  • You're wrapping a resource that is already global, such as process environment or a hardware device.

Avoid it when

  • You only want convenient access. Pass the object in (dependency injection) instead.
  • Tests need different configurations. A singleton makes every test share one.
  • The "single" instance is really per user, per request or per tenant. That's scoped state, not a singleton.
  • Your app runs in several processes or servers: each one gets its own "singleton" anyway.

Pitfalls

  • Hidden dependencies: functions that reach for the singleton internally can't be understood or tested from their signature.
  • Test pollution: state from one test leaks into the next. If you must, provide a reset hook for tests.
  • Mutable singletons become an unofficial shared database. Keep them read-only where possible.
  • Hot module reload and multiple bundles can create two "singletons". Know your module system.

Alternatives

Module instance

Choose it when you just need one shared object in TypeScript: export const config = loadConfig(). Modules are evaluated once.

Dependency injection

Choose it when you want one instance in production but explicit dependencies and easy substitution in tests.

Facade

Choose it when the goal is a simple entry point to a subsystem, not limiting it to one instance.

Flyweight

Choose it when you need many shared instances, one per distinct value, rather than exactly one.