Singleton Pattern in TypeScript - Complete Guide with Examples

Learn the Singleton design pattern with TypeScript examples. Understand when to use Singleton for database connections, configuration managers, and logging services.

Creational

Detailed Explanation

Singleton Pattern

The Singleton pattern ensures a class has exactly one instance and provides a global point of access to it. It is one of the simplest yet most debated design patterns in software engineering.

How It Works

The Singleton pattern works by making the constructor private (or protected) and providing a static method that creates the instance on first call and returns the same instance on subsequent calls.

class AppConfig {
  private static instance: AppConfig | null = null;
  private settings: Map<string, string> = new Map();

  private constructor() {}

  static getInstance(): AppConfig {
    if (!AppConfig.instance) {
      AppConfig.instance = new AppConfig();
    }
    return AppConfig.instance;
  }

  set(key: string, value: string) {
    this.settings.set(key, value);
  }

  get(key: string): string | undefined {
    return this.settings.get(key);
  }
}

Key Characteristics

  • Lazy initialization: The instance is created only when first requested, saving resources during startup.
  • Global access: Any part of the application can access the same instance through the static method.
  • Thread safety: In concurrent environments, extra care (locks, double-checked locking) is needed to prevent multiple instances.

Common Pitfalls

Singletons introduce global state, which makes unit testing harder because tests share the same instance. In modern frameworks, dependency injection containers often replace the Singleton pattern by managing object lifecycles centrally. If you find yourself reaching for Singleton, consider whether dependency injection might be a better fit.

When NOT to Use

Avoid Singleton when you might need multiple instances in the future, when it makes your code harder to test, or when it hides dependencies between classes.

Use Case

Singleton is commonly used for database connection pools, application configuration managers, logging services, and caching layers where only one instance should manage shared state across the entire application.

Try It — Design Pattern Reference

Open full tool