The Strategy Pattern is a GOF (Gang of Four)
behavioral pattern where the intent is to "define a family of algorithms,
encapsulate each one, and make them interchangeable".
This pattern gives the client the flexibility to solve the same problem using
different algorithms. The client can switch to any algorithm.
In the code below, StrategyContext class accepts the SortType parameter which
gives the client the flexibility to select the algorithm without knowing the
internal implementation. Each algorithm is implemented as a separate class and
its contract is defined by an interface. Any new algorithm to be introduced has
to obey the contract defined by the interface.
Source Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPatterns
{
// Interface with alogorithm definition
public interface ISort
{
void Sort();
}
// Class encapsulating algorithm
public class BubbleSort : ISort
{
#region ISort Members
public void Sort()
{
Console.WriteLine("Bubble Sort");
}
#endregion
}
public class ShellSort : ISort
{
#region ISort Members
public void Sort()
{
Console.WriteLine("Shell Sort");
}
#endregion
}
// Context class for clients to interact and call appropriate
// strategy algorithm
public class StrategyContext
{
private ISort sortType;
public StrategyContext()
{
}
public StrategyContext(ISort _sortType)
{
sortType = _sortType;
}
public ISort SortType
{
get { return sortType; }
set { sortType = value; }
}
// Execute the algorithm
public void PerformAction()
{
if (sortType != null)
sortType.Sort();
else
{
throw new Exception("Sort type not defined for the Context");
}
}
}
/// <summary>
/// Client which calls the algorithm
/// </summary>
public class Client
{
static void Main()
{
StrategyContext context = new StrategyContext(new BubbleSort());
context.PerformAction();
context = new StrategyContext();
ShellSort shellSort = new ShellSort();
context.SortType = shellSort;
context.PerformAction();
Console.ReadLine();
}
}
}