Strategy Pattern Guide

Discover how to implement and apply Strategy design patterns to create flexible, maintainable software solutions.

Core Principles

What is Strategy Pattern?

The Strategy Pattern enables selecting algorithms at runtime by encapsulating related operations into interchangeable components. It allows dynamic switching between payment methods, sorting algorithms, or authentication strategies without altering core business logic.

Key Components

  • Strategy Interface - Defines common operations for all algorithm variations
  • Concrete Strategies - Implement specific algorithms
  • Context Class - Maintains reference to current strategy

Implementation Example

Strategy Interface

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

  pay(amount) {
    throw new Error('This method must be implemented');
  }
}
                

Concrete Strategies

class CreditCard extends PaymentStrategy {
  constructor(cardNumber) {
    super();
    this.cardNumber = cardNumber;
  }

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

class PayPal extends PaymentStrategy {
  constructor(email) {
    super();
    this.email = email;
  }

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

Context Usage


        

Real-World Applications

💳 Payment Systems

  • Allow dynamic switching between payment methods
  • Support multiple payment providers without tightly coupling code

📊 Data Compression

  • Support various compression algorithms (gzip, zip, bzip2)
  • Allow runtime selection of compression level

🚀 Game AI

  • Implement different AI behaviors per game character
  • Easily switch between combat/defense strategies during runtime

Common Questions

When to use Strategy vs State pattern?

How to manage strategy dependencies?