Strategy Design Pattern

Introduction:
Sometimes you want your object to behave differently if its internal status changed. The strategy Design pattern enables client code to choose which behavior from a family of behaviors and give client code a simple way to enable that behavior.
Example:

Strategy

 

interface ISortStrategy
{
string Sort();
}

public string Sort()
{
return “0 1 2 3 4 5 6 7 8 9 “; //Simulate sorting algorithm
}

public string Sort()
{
return “9 8 7 6 5 4 3 2 1 0”; //Simulate sorting algorithm
}

class DataList
{
public ISortStrategy strategy;
public DataList(ISortStrategy strategy)
{
this.strategy = strategy;
}
public string GetSortedList()
{
return strategy.Sort();
}
}
static void Main()
{
DataList data = new DataList(new SortAcsStrategy());
Console.WriteLine(data.GetSortedList());
data.strategy = new SortDescStrategy();
Console.WriteLine(data.GetSortedList());
Console.ReadKey();
}

 

Download Code

Leave a Reply

Your email address will not be published.