Design Patterns in JSAdvanced
1Question 1 of 1
javascript

What are common Design Patterns in JavaScript (Singleton, Factory, Observer)?

Explanation & Concept

Design patterns provide battle-tested architectural templates for common software problems:

• Singleton: Guarantees a class has only one instance and provides a global access point. • Factory: Delegates object creation to a function without specifying the exact class. • Observer (Pub/Sub): An object (subject) maintains a list of subscribers and notifies them automatically of state changes.

Code Example
javascript
// Observer Pattern Implementation
class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(eventName, listener) {
    if (!this.events[eventName]) this.events[eventName] = [];
    this.events[eventName].push(listener);
    return () => {
      this.events[eventName] = this.events[eventName].filter((l) => l !== listener);
    };
  }

  emit(eventName, data) {
    if (this.events[eventName]) {
      this.events[eventName].forEach((listener) => listener(data));
    }
  }
}

const emitter = new EventEmitter();
const unsubscribe = emitter.on("userLogin", (user) => console.log("Welcome,", user));
emitter.emit("userLogin", "Riley"); // Logs: "Welcome, Riley"
How It Works & Key Takeaways

The Observer pattern decouples components: the triggering code (`emitter.emit`) has no direct knowledge or dependency on the consuming listeners.