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(); // 1State accumulated through one reference is visible everywhere the singleton is used.
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'