Monday, May 16, 2011

Stratey design pattern

Strategy design pattern, also known as Policy,is a behavioral design pattern.

Intent:
  • Encapsulates the algorithms to make them interchangeable from clients.


Scope:
  • When there are multiple algorithms which need to be interchangeable
  • Many related classes differ only in their behavior;to configure multiple behavior of the classes
Participants:
  • strategy
  • concrete strategy
  • context
Structure:


fig.UML Diagram

Sample Code:

Strategy:

abstract class SortStrategy
{
public abstract void Sort(List list)
}

Concrete Strategy:

class Quicksort:Sortstrategy
{
public overrid void Sort(Listlist)
{
Console.WriteLine("
Quicksort")
}
}

class SheellSort:SortStrategy
{

{
Console.WriteLine("SheellSort")

}

Context:

class SortContext
{
private List list=new
List();
private Strategy sortStrategy;
public void SetSortStrategy(SortStrategy sortStrategy)
{
this.sortStrategy=sortStrategy;
}
public void Add(string name)
{
list.Add(name);
}
public void Sort()
{
sortStrategy.Sort(list);
}


Client:

static void Main()
{
SortContext s=new SortConext();
s.Add("car");
s.Add("bus");
s.SetSortStrategy(new QuickSort());
s.Sort();
s.SetSortStrategy(new ShellSort());
s.Sort();
}






No comments:

Post a Comment