JS Built-ins
DesignPatternsintermediate

Singleton β€” State preservation

πŸ“– Usage Example
class Counter {
  static #inst;
  #count = 0;
  increment() { this.#count++; }
  value() { return this.#count; }
  static getInstance() { return Counter.#inst ?? (Counter.#inst = new Counter()); }
}
Counter.getInstance().increment();
Counter.getInstance().value(); // 1

State accumulated through one reference is visible everywhere the singleton is used.

Singleton β€” Preserving State Across Calls

A key feature of the Singleton pattern is that state is preserved. Multiple calls to getInstance return the same object with the same data.

Challenge: Create a StateManager singleton that stores and retrieves state. Each getInstance should return the same state object.

Example:

const state1 = StateManager.getInstance()
state1.data = 'hello'
const state2 = StateManager.getInstance()
state2.data // 'hello'
πŸ’‘ Hints (3)
  • β€’ Initialize data properties in constructor
  • β€’ All getInstance calls return the same instance
  • β€’ Modifications to the instance affect all references