📘 Design Patterns Reference

Comprehensive documentation of essential design patterns with practical code examples and implementation strategies.

Core Patterns

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable.

{`class PaymentStrategy {
  pay(amount) {
    throw new Error("Should be implemented");
  }
}

class CreditCardStrategy extends PaymentStrategy {
  pay(amount) {
    console.log("Credit card processed $", amount);
  }
}

class PayLaterStrategy extends PaymentStrategy {
  pay(amount) {
    console.log("Pay later scheduled for $", amount);
  }
}

class PaymentContext {
  constructor(strategy) {
    this.strategy = strategy;
  }
  setStrategy(strategy) {
    this.strategy = strategy;
  }
  executePayment(amount) {
    this.strategy.pay(amount);
  }
}

const context = new PaymentContext(new CreditCardStrategy());
context.executePayment(150);
context.setStrategy(new PayLaterStrategy());
context.executePayment(75);`}

Observer Pattern

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.

{`class Subject {
  constructor() {
    this._observers = [];
  }
  registerObserver(observer) {
    this._observers.push(observer);
  }
  notifyObservers(data) {
    this._observers.forEach(obs => obs.update(data));
  }
}

class TemperatureDisplay {
  update(temp) {
    console.log("Temperature updated:", temp);
  }
}

const weatherStation = new Subject();
const display1 = new TemperatureDisplay();
const display2 = new TemperatureDisplay();
weatherStation.registerObserver(display1);
weatherStation.registerObserver(display2);
weatherStation.notifyObservers(72);`}

Advanced Patterns

Explore complex patterns in our Advanced Design Patterns Tutorial.