Day 43

Design Patterns — Singleton Pattern

10 min
JavaScript 100 Days

Singleton pattern ensure karta hai ke ek class ka sirf ek instance ho. Config manager, database connection, cache — sab ke liye singleton use hota hai.

Singleton Implementation

One instance, global access.

singleton.js
javascript
class Config {
  constructor() {
    if (Config.instance) {
      return Config.instance; // same instance return karo!
    }
    this.settings = {
      theme: "dark",
      language: "ur",
      apiUrl: "https://api.example.com"
    };
    Config.instance = this;
  }
  
  get(key) { return this.settings[key]; }
  set(key, value) { this.settings[key] = value; }
}

// Same instance milegi — naya nahi banega
const config1 = new Config();
const config2 = new Config();

config1.set("theme", "light");
console.log(config2.get("theme")); // "light" — same object!
console.log(config1 === config2);  // true

🎯 Practice Challenge

Logger singleton banao — log level (info/warn/error), message history store karo, getLogs() method. Sab jagah same instance use ho.