Saturday, December 7, 2013

Strategy Pattern

Directly from the Strategy Pattern Wikipedia article:

The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.

Let's see how it works using C# language. In my sample i show you as we can change the Sort Algorithm using a Context class to implement this swap.

namespace StrategySample
{
public interface IStrategy
{
List<string> SortData(List<string> inputData);
}
        // We declare a class to implement QuickSort ordering algorithm
public class QuickSort : IStrategy
{
public List<string> SortData(List<string> inputData)
{
List<string> sortedData = new List<string>();
// do QuickSort algorithm to sort data
return sortedData;
}
}
       // We declare a class to implement BubbleSort ordering algorithm
public class BubbleSort : IStrategy
{
public List<string> SortData(List<string> inputData)
{
List<string> sortedData = new List<string>();
// do BubbeSort algorithm to sort data
return sortedData;
}
}
       // We declare a class to implement the context for sorting
public class SortContext
{
IStrategy _strategSort;

public SortContext(IStrategy strategy)
{
_strategSort = strategy;
}
public List<string> Sort(List<string> inputData)
{
return _strategSort.SortData(inputData);
}
}
}

Now let's see the pattern in action

static void Main(string[] args)
{
        SortContext context;
        List<string> data = new List<string>();
        List<string> sortedData =  context.Sort(data);
        // Create the inputData
data.Add("string one");
data.Add("string two");

        // We apply QuickSort algorithm
context = new SortContext(new QuickSort());
        sortedData = context.Sort(data);
foreach (var item in sortedData)
{
Console.WriteLine(item);
}

         // We apply BubbleSort algorithm
context = new SortContext(new BubbleSort());
sortedData = context.Sort(data);
foreach (var item1 in sortedData)
{
Console.WriteLine(item1);
}
}

Basically we inject the Interface implementation into the Context Strategy class and we use polymorphism to run the different behavior.

No comments:

Post a Comment