Skip to content
BBaskaran

Singleton

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

Use it when

Exactly one shared resource is needed, such as a logger, configuration or connection pool.

/**
 * Singleton: one application-wide Logger shared by every service.
 *
 * Real-world scenario: an e-commerce backend where the order service and the
 * payment service both log through the same Logger, so all log lines end up in
 * one place with one configuration.
 *
 * JavaScript runs your code on a single thread, so unlike the Python version
 * this needs no lock: getInstance() can't be called twice at the same moment.
 */

class Logger {
  private static instance: Logger | undefined;

  private readonly appName: string;
  private readonly history: string[] = [];

  // private: `new Logger()` outside this class is a compile error,
  // so getInstance() is the only way to get a logger.
  private constructor(appName: string) {
    this.appName = appName;
  }

  static getInstance(appName = "shop-api"): Logger {
    // Create the instance on first use; later calls return the same one.
    Logger.instance ??= new Logger(appName);
    return Logger.instance;
  }

  info(message: string, source: string): void {
    this.log("INFO", message, source);
  }

  error(message: string, source: string): void {
    this.log("ERROR", message, source);
  }

  get historySize(): number {
    return this.history.length;
  }

  private log(level: string, message: string, source: string): void {
    const line = `[${this.appName}] ${level.padEnd(5)} ${source}: ${message}`;
    this.history.push(line);
    console.log(line);
  }
}

class OrderService {
  readonly logger = Logger.getInstance();

  placeOrder(orderId: string, amount: number): void {
    this.logger.info(`Order ${orderId} placed for $${amount.toFixed(2)}`, "OrderService");
  }
}

class PaymentService {
  // A different argument is ignored: the instance already exists.
  readonly logger = Logger.getInstance("payments");

  charge(orderId: string, cardOk: boolean): void {
    if (cardOk) {
      this.logger.info(`Payment captured for ${orderId}`, "PaymentService");
    } else {
      this.logger.error(`Card declined for ${orderId}`, "PaymentService");
    }
  }
}

function clientCode(): void {
  const orders = new OrderService();
  const payments = new PaymentService();

  orders.placeOrder("ORD-1001", 49.99);
  payments.charge("ORD-1001", true);
  orders.placeOrder("ORD-1002", 120);
  payments.charge("ORD-1002", false);

  console.log("Same logger instance:", orders.logger === payments.logger);
  console.log("Shared history size:", Logger.getInstance().historySize);

  // new Logger("other"); // ✗ compile error: constructor of 'Logger' is private
}

clientCode();

// Output:
// [shop-api] INFO  OrderService: Order ORD-1001 placed for $49.99
// [shop-api] INFO  PaymentService: Payment captured for ORD-1001
// [shop-api] INFO  OrderService: Order ORD-1002 placed for $120.00
// [shop-api] ERROR PaymentService: Card declined for ORD-1002
// Same logger instance: true
// Shared history size: 4

How it works

RoleClassesWhat it does
SingletonLoggerPrivate constructor; getInstance() creates the instance once and returns it every time
ClientsOrderService, PaymentServiceEach calls getInstance() and shares one logger and one history