Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Design Pattern
  4. / Lessons
  5. / 1

Prev

Strategy Pattern

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows a client to choose which algorithm to use at runtime.

When to Use:

Use the Strategy pattern when you have multiple algorithms for a specific task and you want to choose the appropriate algorithm at runtime.

Example

// PaymentStrategy Interface
interface PaymentStrategy {
pay(amount: number): void;
}
// Concrete Strategies
class CreditCardPayment implements PaymentStrategy {
pay(amount: number): void {
console.log(`Paid ${amount} using Credit Card`);
}
}
class PayPalPayment implements PaymentStrategy {
pay(amount: number): void {
console.log(`Paid ${amount} using PayPal`);
}
}
// Context
class PaymentProcessor {
private strategy: PaymentStrategy;
constructor(strategy: PaymentStrategy) {
this.strategy = strategy;
}
setStrategy(strategy: PaymentStrategy) {
this.strategy = strategy;
}
processPayment(amount: number) {
this.strategy.pay(amount);
}
}
// Usage
const processor = new PaymentProcessor(new CreditCardPayment());
processor.processPayment(100);
processor.setStrategy(new PayPalPayment());
processor.processPayment(150);

Pros:

  • Promotes Open/Closed Principle.
  • Easy to switch between different algorithms.

Cons:

  • Increases the number of classes in the application.
  • Clients must be aware of different strategies.

Prev