The Strategy Design Pattern is a behavioral design pattern that defines a family of algorithms, encapsulates each one, and makes them interchangeable. It allows you to select the algorithm to use dynamically at runtime, and it separates the algorithm’s implementation from the client code. This pattern is useful when you want to decouple the algorithm from the context that uses it.
Here’s a C# example of the Strategy Design Pattern with a use case for sorting a list of items using different sorting algorithms:
Create the Strategy Interface
Define an interface that represents the strategy. This interface declares a method that encapsulates the algorithm.
public interface ISortStrategy
{
void Sort(int[] data);
}
Create Concrete Strategies
Implement concrete classes that inherit from the strategy interface, each representing a specific sorting algorithm.
public class BubbleSort : ISortStrategy
{
public void Sort(int[] data)
{
Console.WriteLine("Sorting using Bubble Sort");
// Implement the Bubble Sort algorithm
}
}
public class QuickSort : ISortStrategy
{
public void Sort(int[] data)
{
Console.WriteLine("Sorting using Quick Sort");
// Implement the Quick Sort algorithm
}
}
public class MergeSort : ISortStrategy
{
public void Sort(int[] data)
{
Console.WriteLine("Sorting using Merge Sort");
// Implement the Merge Sort algorithm
}
}
Create the Context Class
Define a context class that holds a reference to the strategy interface and uses it to execute the selected algorithm.
public class SortContext
{
private ISortStrategy strategy;
public SortContext(ISortStrategy strategy)
{
this.strategy = strategy;
}
public void SortData(int[] data)
{
strategy.Sort(data);
}
}
Use Case – Sorting a List of Numbers
Use the Strategy Design Pattern to sort a list of numbers using different sorting algorithms dynamically.
class Program
{
static void Main(string[] args)
{
int[] data = { 5, 2, 8, 1, 9, 4 };
SortContext context = new SortContext(new BubbleSort());
context.SortData(data);
context = new SortContext(new QuickSort());
context.SortData(data);
context = new SortContext(new MergeSort());
context.SortData(data);
}
}
In this example, the Strategy Design Pattern allows you to sort a list of numbers using different sorting algorithms (Bubble Sort, Quick Sort, Merge Sort) by dynamically selecting the strategy at runtime. The client code (the SortContext
) is decoupled from the specific sorting algorithms, making it easy to switch between algorithms without modifying the client code.