Link copied to clipboard!
Strategy
Swap algorithm objects to vary behavior.
C#
// Strategy interface
interface ISort
{
int[] Sort(int[] a);
}
// Concrete strategy: ascending
class Asc : ISort
{
public int[] Sort(int[] a)
{
var copy = a.ToArray();
Array.Sort(copy);
return copy;
}
}
// Concrete strategy: descending
class Desc : ISort
{
public int[] Sort(int[] a)
{
var copy = a.ToArray();
Array.Sort(copy, (x, y) => y.CompareTo(x));
return copy;
}
}
// Context holding a strategy reference
class Ctx
{
private ISort _strategy;
public Ctx(ISort s) => _strategy = s;
public int[] Do(int[] a) => _strategy.Sort(a);
public void Set(ISort s) => _strategy = s; // swap at runtime
}
// Usage
var ctx = new Ctx(new Asc());
var r1 = ctx.Do(new[] { 3, 1, 2 }); // 1,2,3
ctx.Set(new Desc());
var r2 = ctx.Do(new[] { 3, 1, 2 }); // 3,2,1
next