Strategy Pattern in TypeScript

๐Ÿ‘€ Views 12.5K
๐Ÿ”„ Shares 847
โฐ Read time 7 min

The Strategy Pattern is a behavioral design pattern that enables selecting an algorithmโ€™s behavior at runtime. Instead of embedding algorithms directly into classes, we define them as separate objects (strategies) and make them interchangeable.

This pattern is widely used in scenarios like:

  • Payment processing (credit card vs. PayPal)
  • Sorting algorithms (quick sort vs. merge sort)
  • Navigation systems (driving vs. walking directions)

In TypeScript, interfaces and classes make implementing the Strategy Pattern straightforward and type-safe.


๐Ÿ”น Why It Matters

  • Flexibility: Change behaviors dynamically without modifying existing code.
  • Maintainability: Avoid conditional statements (if-else/switch) that clutter code.
  • Testability: Isolate strategies for easier unit testing.
  • Open/Closed Principle: Extend behavior without modifying existing classes.

๐Ÿ”น Core Concepts

The Strategy Pattern consists of three main components:

  1. Context: Holds a reference to a strategy and delegates work to it.
  2. Strategy Interface: Defines a common method that all strategies implement.
  3. Concrete Strategies: Implement the interface with specific behaviors.

Strategy Pattern UML Diagram
Source: medium


๐Ÿ”น Code Walkthrough

Example: Payment Processor

Weโ€™ll create a payment system that supports different payment methods (Credit Card, PayPal).

1. Define the Strategy Interface

// PaymentStrategy.ts
interface PaymentStrategy {
  pay(amount: number): string; // All strategies must implement this method
}

2. Implement Concrete Strategies

// CreditCardPayment.ts
class CreditCardPayment implements PaymentStrategy {
  pay(amount: number): string {
    return `Paid ${amount} USD via Credit Card.`;
  }
}

// PayPalPayment.ts
class PayPalPayment implements PaymentStrategy {
  pay(amount: number): string {
    return `Paid ${amount} USD via PayPal.`;
  }
}

3. Create the Context Class

// PaymentProcessor.ts
class PaymentProcessor {
  private strategy: PaymentStrategy; // Reference to the current strategy

  constructor(strategy: PaymentStrategy) {
    this.strategy = strategy;
  }

  setStrategy(strategy: PaymentStrategy): void {
    this.strategy = strategy; // Dynamically switch strategies
  }

  executePayment(amount: number): string {
    return this.strategy.pay(amount); // Delegate payment to the strategy
  }
}

4. Use the Pattern

// main.ts
const creditCardPayment = new CreditCardPayment();
const payPalPayment = new PayPalPayment();

const processor = new PaymentProcessor(creditCardPayment);
console.log(processor.executePayment(100)); // Paid 100 USD via Credit Card.

processor.setStrategy(payPalPayment);
console.log(processor.executePayment(50)); // Paid 50 USD via PayPal.

๐Ÿ”น Common Mistakes

  1. Overusing the Pattern: Not every conditional needs a strategy. Use it only when behaviors change frequently.
  2. Tight Coupling: If strategies depend on the context, consider dependency injection.
  3. Performance Overhead: Creating many small strategy classes can increase complexity.

๐Ÿ”น Best Practices

โœ… Keep strategies stateless if possible (avoid storing unnecessary data).
โœ… Use dependency injection for better testability.
โœ… Document strategy interfaces clearly to avoid confusion.


๐Ÿ”น Final Thoughts

The Strategy Pattern is a powerful tool for writing flexible, maintainable, and testable TypeScript applications. By decoupling algorithms from their clients, you can easily extend functionality without modifying existing code.

For further reading:


Happy coding! ๐Ÿš€


Strategy Pattern TypeScript Design Patterns OOP Behavioral Patterns Software Architecture

Related Articles

Command Pattern in TypeScript

Command Pattern in TypeScript

Learn the Command Pattern in TypeScript with real-world examples, code walkthroughs, and best practices for decoupling actions in your applications.

Command PatternTypeScriptDesign PatternsSoftware Engineering
Abstract Factory Pattern in TypeScript

Abstract Factory Pattern in TypeScript

Master the Abstract Factory Pattern in TypeScript with clear explanations, real-world examples, and best practices. Learn how to create families of related objects efficiently.

Abstract Factory Pattern Design Patterns Object Creation TypeScript Tutorial
Observer Pattern in TypeScript

Observer Pattern in TypeScript

Master the Observer Pattern in TypeScript with clear explanations, real-world examples, and best practices for building reactive applications.

Observer PatternDesign PatternsReactive ProgrammingEvent Handling
Strategy Pattern in TypeScript

Strategy Pattern in TypeScript

Learn the Strategy Pattern in TypeScript with real-world examples, code walkthroughs, and best practices.

Strategy Pattern TypeScript Design Patterns OOP
Factory Pattern in TypeScript

Factory Pattern in TypeScript

Learn how to implement the Factory Pattern in TypeScript to create flexible and scalable applications. This guide includes real-world examples, common pitfalls, and best practices.

Factory Pattern Design Patterns Object Creation Software Engineering
Load more articles