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
- strategy
- concrete strategy
- context
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();
}
Strategy:
abstract class SortStrategy
{
public abstract void Sort(List
}
Concrete Strategy:
class Quicksort:Sortstrategy
{
public overrid void Sort(List
{
Console.WriteLine("
}
}
class SheellSort:SortStrategy
{
{
Console.WriteLine("SheellSort")
Context:
class SortContext
{
private 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.SetSortStrategy(new QuickSort());
s.Sort();
s.SetSortStrategy(new ShellSort());
s.Sort();