JS Built-ins
DesignPatternsbeginner

Singleton β€” Static property

πŸ“– Usage Example
class DB {
  static instance = null;
  static getInstance() {
    return DB.instance ?? (DB.instance = new DB());
  }
}
DB.getInstance() === DB.getInstance(); // true

Singleton ensures only one instance exists β€” getInstance always returns the same object.

Singleton Pattern β€” Static Property Approach

The Singleton pattern restricts a class to have only one instance. One common approach is using a static property to cache the instance.

Challenge: Implement a Database class with a static getInstance() method that returns the same instance every time it's called.

Example:

const db1 = Database.getInstance()
const db2 = Database.getInstance()
db1 === db2 // true
πŸ’‘ Hints (3)
  • β€’ Use a static property to store the instance
  • β€’ Use the nullish coalescing operator (??)
  • β€’ getInstance should check if instance exists before creating