← Back to Home

Singleton Pattern

Ensure a class has only one instance and provide a global access point.

What is it?

The Singleton pattern ensures there is only one instance of a class throughout the app, and provides a global point of access to that instance.

Interactive Demo: Singleton vs Regular Class

Click the buttons below to see the difference between Singleton and regular class instantiation:

🔒 Singleton Pattern

Instances Created:0

🔓 Regular Class

Instances Created:0

💡 Notice the Difference:

  • Singleton: Always returns the same instance (same ID, count stays low)
  • Regular Class: Creates new instances every time (different IDs, count increases)

Code Example

class ToastManager {
  private static instance: ToastManager;
  private constructor() {} // Private constructor prevents direct instantiation
  
  static getInstance(): ToastManager {
    if (!ToastManager.instance) {
      ToastManager.instance = new ToastManager();
    }
    return ToastManager.instance; // Always returns the same instance
  }
  
  show(message: string) {
    toast.success(message);
  }
}

// Usage - both variables point to the same instance
const toast1 = ToastManager.getInstance();
const toast2 = ToastManager.getInstance();
console.log(toast1 === toast2); // true

Common Uses

  • Global toast manager
  • Application-wide theme or settings service
  • Redux store or centralized event bus
  • Database connection pools
  • Logging services

When to Use

  • Need exactly one instance of a class
  • Shared global state or utilities
  • Expensive object creation that should be done once
  • Coordinating actions across the system

Caution

  • Overuse can lead to tightly coupled code
  • Harder to test if used improperly
  • Can create hidden dependencies
  • Violates Single Responsibility Principle if it does too much