JS Built-ins
DesignPatternsadvanced

Singleton β€” Multiple independent singletons

πŸ“– Usage Example
class Pool {
  static #inst;
  #connections = [];
  add(c) { this.#connections.push(c); }
  size() { return this.#connections.length; }
  static getInstance() { return Pool.#inst ?? (Pool.#inst = new Pool()); }
}

Resource pools (connections, workers) are a classic singleton use case.

Singleton β€” Different Singletons Are Independent

Each class can have its own singleton instance. Two different singleton classes should maintain separate instances.

Challenge: Create two different singleton classes: Database and Cache. Each should have its own independent getInstance method. Verify they are different instances.

Example:

const db = Database.getInstance()
const cache = Cache.getInstance()
db !== cache // true
Database.getInstance() === Database.getInstance() // true
Cache.getInstance() === Cache.getInstance() // true
πŸ’‘ Hints (3)
  • β€’ Each class needs its own static instance property
  • β€’ Each class needs its own getInstance method
  • β€’ Different classes are independent