Strategy Pattern

Posted: December 1, 2010 in Design Patterns

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”);
}
}

}

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();
}
}
}

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s