Posts

Singleton

June 13, 2025
Singleton Pattern
The Singleton Pattern makes sure a class has only one instance and gives you a way to access that instance from anywhere in your code.
Two main reasons:
  1. Only one instance should exist (e.g., a database connection).
  2. You want a global access point, but safer than using a global variable.
Instead of creating new objects every time with new, the Singleton gives you the same object every time you call it.
Think of a government in a country. You can only have one official government. No matter who runs it, there's just one, and everyone refers to the same thing.
Javascript
class Database {
  // Private static variable to hold the single instance
  static #instance = null;

  // Private constructor
  constructor() {
    if (Database.#instance) {
      throw new Error("Use Database.getInstance() instead of new.");
    }
    console.log("Connecting to the database...");
    // setup code here
  }

  // Static method to get the instance
  static getInstance() {
    if (!Database.#instance) {
      Database.#instance = new Database();
    }
    return Database.#instance;
  }

  // Example method
  query(sql) {
    console.log(`Running query: ${sql}`);
  }
}

// Usage
const db1 = Database.getInstance();
db1.query("SELECT * FROM users");

const db2 = Database.getInstance();
db2.query("SELECT * FROM orders");

console.log(db1 === db2); // true - same instance

  • You can’t use new Database() because the constructor is private.
  • You must use Database.getInstance() to get the object.
  • Every time you call getInstance(), you get the same object.

Use Singleton when:
  • You only want one object (e.g., logger, config, database).
  • You want that object to be accessible globally.
  • You want to control creation of the object.

✅ Pros:
  • You get a single, consistent instance.
  • Global access with controlled creation.
  • Can delay creation until needed (lazy).
❌ Cons:
  • Breaks Single Responsibility Principle (does two things).
  • Can be hard to unit test or mock.
  • In multithreading, extra care is needed to avoid multiple instances.
On this page