Strategy Pattern

A behavioral design pattern that lets you define a family of algorithms, encapsulate each one, and make them interchangeable. Allows switching between algorithms at runtime.

Key Concepts

  • Strategy defines common interface for algorithms
  • Concrete strategies implement different algorithms
  • Context maintains reference to strategy interface
  • Supports dynamic algorithm switching

Implementation Example

Strategy Interface

class PaymentStrategy {
  constructor() {
    this.type = 'base';
  }

  // Abstract method to process payment
  pay(amount) {
    throw new Error('This method must be implemented');
  }
}
                        

Concrete Strategies

class CreditCardPayment extends PaymentStrategy {
  constructor(cardNumber) {
    super();
    this.cardNumber = cardNumber;
    this.type = 'creditCard';
  }

  // Process credit card payment
  pay(amount) {
    return `Processed $${amount} via credit card ending in ***${this.cardNumber.slice(-4)}`;
  }
}

class PayPalPayment extends PaymentStrategy {
  constructor(email) {
    super();
    this.email = email;
    this.type = 'paypal';
  }

  // Process PayPal payment
  pay(amount) {
    return `Processed $${amount} via PayPal for ${this.email}`;
  }
}
                        

Context Usage


                    

Frequently Asked Questions

When should I use this pattern?

How is it different from other patterns?

What are common use cases?