Strategy Design Pattern


Here, we will see how to create Strategy Design Pattern with example.

Strategy Design Pattern

Overview

The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern allows the algorithm to vary independently from clients that use it. The key idea is to delegate the responsibility of selecting an algorithm to separate classes (strategies), which can be used interchangeably based on the client's needs.

Example

A payment processing system where we need to provide different payment methods, such as credit cards, PayPal, and bank transfers.

Strategy Design Pattern

Advantages of the Strategy Pattern

  1. Separation of Concerns -  The Strategy pattern helps to separate the algorithm from the context where it's used, making the system more modular and easier to maintain.
  2. Open/Closed Principle -  It allows adding new algorithms (strategies) without modifying the existing code, adhering to the Open/Closed Principle.
  3. Eliminates Conditional Logic -  Instead of using multiple if-else or switch statements to choose between algorithms, the Strategy pattern provides a cleaner approach with polymorphism.
  4. Code Reusability -  Since each strategy is encapsulated in a separate class, these can be reused in other contexts without duplicating code.
  5. Flexible & Extensible -  It’s easy to extend the system by introducing new strategies or replacing old ones without impacting the core logic.

When to Use the Strategy Pattern

  • When a class needs to perform similar behavior using different algorithms, and you want to be able to switch between them dynamically.
  • When you have multiple if-else or switch statements scattered throughout your code that select different behaviors or algorithms.
  • When you need to replace algorithms in the system without changing the client code.
  • When you want to reduce coupling between the client and the algorithm it uses, promoting flexibility and scalability.

Problems in a System Without the Strategy Pattern

  1. Tight Coupling -  Without the Strategy pattern, the algorithm is hardcoded in the client class, leading to tight coupling between the client and the behavior.
  2. Difficult Maintenance -  As more algorithms are added, you will need to modify the client code every time, violating the Open/Closed Principle.
  3. Code Duplication -  Different areas of the code that use different algorithms may result in code duplication or bloated classes with many methods for each algorithm.
  4. Complex Conditional Logic -  Without the Strategy pattern, you often end up with long if-else or switch statements, making the code harder to read, understand, and maintain.

Example of Strategy Pattern

Let's take the example of a payment processing system where we need to provide different payment methods, such as credit cards, PayPal, and bank transfers.

// Strategy Interface
public interface IPaymentStrategy
{
    void Pay(decimal amount);
}

// Concrete Strategy for Credit Card
public class CreditCardPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount} using Credit Card.");
    }
}

// Concrete Strategy for PayPal
public class PayPalPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount} using PayPal.");
    }
}

// Context that uses the Strategy
public class PaymentContext
{
    private IPaymentStrategy _paymentStrategy;

    public void SetPaymentMethod(IPaymentStrategy paymentStrategy)
    {
        _paymentStrategy = paymentStrategy;
    }

    public void MakePayment(decimal amount)
    {
        _paymentStrategy.Pay(amount);
    }
}

// Usage
public class Program
{
    public static void Main(string[] args)
    {
        PaymentContext context = new PaymentContext();

        // Paying with Credit Card
        context.SetPaymentMethod(new CreditCardPayment());
        context.MakePayment(100m);

        // Paying with PayPal
        context.SetPaymentMethod(new PayPalPayment());
        context.MakePayment(200m);
    }
}

Output

Strategy Design Pattern

Real-World Example of Strategy Pattern

  1. Sorting Algorithms in Libraries - Many libraries use the Strategy pattern for sorting algorithms. A sorting algorithm (such as quicksort, mergesort, or bubblesort) can be chosen dynamically based on data size or other parameters.
  2. Compression Algorithms - Applications like file archivers (e.g., WinRAR, 7-Zip) allow users to choose different compression strategies (e.g., ZIP, RAR, or 7z) depending on the file type and user preference.
  3. Navigation Systems - In GPS navigation systems, different route-finding strategies like the shortest route, fastest route, or avoiding highways can be selected based on the user’s needs. Each of these strategies is implemented separately and can be swapped dynamically.
  4. Payment Gateways - E-commerce platforms typically implement various payment methods, such as PayPal, Stripe, and credit cards, using the Strategy pattern. The platform can select the appropriate payment method (strategy) based on user choice, location, or transaction type.

Prev Next

Top Articles

  1. What is JSON
  2. How to convert a javaScript object in JSON object
  3. Some Important JSON Examples
  4. Common JSON Interview Question