Programming Language
JavaScript
Advanced JavaScript
Design Patterns
Singleton Pattern

Singleton Pattern

A Singleton is a design pattern that ensures a class has only one instance and provides a global point of access to it.


1. The Analogy: The Office Manager

In a company, there is usually only one Office Manager.

  • If a developer needs a new monitor, they talk to the Office Manager.
  • If an intern needs a keycard, they talk to the same Office Manager.
  • You don't hire a new Office Manager every time someone needs something; you always go to the one that already exists.

2. Coding Example: The Database Connection

In your app, you probably only want one database connection object to avoid wasting resources.

Singleton Implementation

let instance;
 
class DatabaseConnector {
  constructor() {
    if (instance) {
      throw new Error("You can only have one Database Connection!");
    }
    this.connection = "Connected to MongoDB";
    instance = this;
  }
 
  static getInstance() {
    if (!instance) {
      instance = new DatabaseConnector();
    }
    return instance;
  }
}
 
const db1 = DatabaseConnector.getInstance();
const db2 = DatabaseConnector.getInstance();
 
console.log(db1 === db2); // true - They are the exact same object!

3. Why it matters in Coding

  1. Resource Protection: It prevents your app from creating 100 connections to a database or a file system, which would slow it down.
  2. Consistency: It ensures that every part of your app is reading the same configuration or data.
  3. Global State: It’s often used for things like "User Settings" or "Authentication Tokens" that need to be the same across the entire application.

Real-Life Coding Scenario: The Logger

You want a Logger that writes all error messages to a single file. By using a Singleton, you ensure that no matter where the error happens, it always goes to the same file managed by the same object.


Summary

ComponentAnalogyTechnical Takeaway
InstanceThe Office ManagerThe single source of truth.
Global AccessThe Manager's DeskEvery part of the app goes to the same place.

The Singleton pattern keeps your system organized by having one "boss" for specific tasks!