Design Patterns : Strategy Pattern

Strategy Pattern lets you create a family of strategies (algorithm) encapsulated into separate interchangeable classes. In our example, we will consider a Client class which needs to invoke different sorting algorithm.

 

Let’s first create the contract interface for different Sorting algorithm.

public interface ISortStrategy
{
   void Sort(int[] ArrayToSort);
}

Now that we have our interface ready, let’s go ahead and implement different sorting algorithms based on it.[/code]

public class QuickSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Quick Sort");
  }
}

public class BubbleSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Bubble Sort");
  }
}

public class MergeSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
    Console.WriteLine("Executing Merge Sort");
  }
}

public class HeapSort : ISortStrategy
{
  public void Sort(int[] ArrayToSort)
  {
   Console.WriteLine("Executing Heap Sort");
  }
}

Now let’s head to our Client Class and Inject the Strategy, which would be used to sort the Array.

internal class Client
{

  private int[] _IntArray;

  public Client(int[] IntArray)
  {
    _IntArray = IntArray;
  }

  public void Sort(ISortStrategy Strategy)
  {
   Strategy.Sort(_IntArray);
  }
}

As you can see , the Client Class is devoid of any direct dependencies as well as any nasty conditional statements. Yes, its a good idea to do away with Conditional Statements , especially those long if-else or switch cases as it can increase the cyclomatic complexity of the code. The Strategy is injected directly in the client, which invokes it.

Complete collection of articles on Design Patterns can be found here

3 thoughts on “Design Patterns : Strategy Pattern

  1. The Strategy is injected directly in the client, which invokes it.

    Yes , it is, but it means the IF-ELSE was moved up to the injector.
    This looks more like DI pattern, than Strategy.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s