JS Built-ins
DesignPatternsintermediate

Singleton β€” Closure-based

πŸ“– Usage Example
class Config {
  #data = {};
  static #instance;
  set(k, v) { this.#data[k] = v; }
  get(k) { return this.#data[k]; }
  static getInstance() { return Config.#instance ?? (Config.#instance = new Config()); }
}

Singletons are ideal for shared configuration stores accessed throughout the app.

Singleton Pattern β€” Closure Approach

Instead of using static properties, we can use a closure (IIFE) to create a private scope and ensure only one instance exists.

Challenge: Implement a closure-based singleton Config object. The getInstance() function should return a cached object that persists across calls.

Example:

const config1 = Config.getInstance()
const config2 = Config.getInstance()
config1 === config2 // true
πŸ’‘ Hints (3)
  • β€’ Use an IIFE to create a private scope
  • β€’ Store instance in a closure variable
  • β€’ Return an object with getInstance method