JS Built-ins
DesignPatternsbeginner

Singleton β€” Lazy initialization

πŸ“– Usage Example
class Logger {
  static #inst = null;
  createdAt = Date.now();
  static getInstance() {
    return Logger.#inst ?? (Logger.#inst = new Logger());
  }
}
// Instance created only on first call

Lazy initialization creates the instance only when first requested.

Singleton β€” Lazy Initialization

Lazy initialization means the singleton instance is only created when it's first requested, not when the class is defined. This saves resources if the instance is never needed.

Challenge: Create a Logger class that creates its instance only on the first getInstance() call. Each instance should store its creation time.

Example:

const log1 = Logger.getInstance()
const log2 = Logger.getInstance()
log1.createdAt === log2.createdAt // true (same instance)
πŸ’‘ Hints (3)
  • β€’ Initialize the instance property to null
  • β€’ Check if instance exists, if not create it
  • β€’ Store initialization metadata in constructor