Observer & Singleton Patterns
How can you implement a Singleton that supports multiple instances for testing?
class TestableSingleton {
static #instances = new Map();
#state;
constructor(key = 'default') {
const existingInstance = TestableSingleton.#instances.get(key);
if (existingInstance) {
return existingInstance;
}
this.#state = {};
TestableSingleton.#instances.set(key, this);
}
static getInstance(key = 'default') {
if (!TestableSingleton.#instances.has(key)) {
new TestableSingleton(key);
}
return TestableSingleton.#instances.get(key);
}
static resetInstances() {
TestableSingleton.#instances.clear();
}
}