Back

Code Flexibility with the Strategy Design Pattern

May 17 2024
10min
šŸ• Current time : 29 Mar 2025, 05:04 AM
The full Astro logo.

Ever feel stuck with an algorithm baked into your code? What if you needed a different approach later? The Strategy design pattern is your knight in shining armor, offering runtime flexibility for choosing algorithms. In this edition, we’ll unveil its magic with clear explanations, real-world use cases and working code example in C#.

The Problem: Algorithm Rigidity

Imagine you code a program to sort a list of numbers. You meticulously craft a sorting algorithm, but what if later you need a different sorting method, like alphabetizing text? You’d be forced to rewrite the sorting logic, a cumbersome and error-prone task.

The Solution: The Strategy Design Pattern

The Strategy pattern separates the algorithm selection from its usage. Here’s the game plan:

  1. Define an Interface: This interface outlines the methods for all possible algorithms (e.g., Sort() for sorting). Think of it as a contract for different algorithms to fulfill.

  2. Create Concrete Strategies: Each concrete strategy class implements the interface, providing its specific algorithm implementation (e.g., BubbleSort, InsertionSort).

  3. The Context Class: This class holds a reference to a strategy object and uses the interface methods to delegate the work. It can switch strategies at runtime as needed.

Benefits Abound

  1. Flexibility: Easily swap algorithms without modifying the context class.

  2. Maintainability: Code becomes more modular and easier to understand.

  3. Testability: Isolate and test each strategy independently.

Use Case: Dynamic Discounts

An e-commerce app can leverage the Strategy pattern to offer various discounts. The DiscountCalculator interface defines a CalculateDiscount() method. Concrete strategies like FlatRateDiscount and PercentageDiscount implement this interface with their specific calculations. The shopping cart context can hold a reference to the chosen strategy and dynamically calculate discounts based on promotions.

C# Code Example: Sorting It Out

Let’s build a simple example in C# to solidify our understanding. Here’s the code for the Strategy pattern applied to sorting numbers.

// Interface for sorting algorithms
public interface ISortingStrategy
{
    void Sort(List<int> numbers);
}

// Concrete strategy - Bubble Sort
public class BubbleSort : ISortingStrategy
{
    public void Sort(List<int> numbers)
    {
        // Implement bubble sort logic here
    }
}

// Concrete strategy - Insertion Sort
public class InsertionSort : ISortingStrategy
{
    public void Sort(List<int> numbers)
    {  
        // Implement insertion sort logic here
    }
}

// Context class - Sorter
public class Sorter
{
    private ISortingStrategy _strategy;

    public Sorter(ISortingStrategy strategy)
    {
        _strategy = strategy;
    }

    public void SortNumbers(List<int> numbers)
    {
        _strategy.Sort(numbers);
    }

    public void SetStrategy(ISortingStrategy strategy)
    {
        _strategy = strategy;
    }
}

In the above example, the Sorter class can hold a reference to any ISortingStrategy object. We can choose between BubbleSort and InsertionSort at runtime and sort the numbers accordingly.

At the End

This design pattern empowers you to design flexible and adaptable code. By separating algorithms and their usage, you gain control over runtime behavior and keep your code maintainable. So, the next time you face a situation demanding algorithmic flexibility, consider the Strategy pattern as your trusty companion. šŸ’”

Read more in this Series:

Find me on

GitHub LinkedIn LinkedIn X Twitter
© 2022 to 2025 : Amit Prakash