Skip to main content

Pattern: Strategy

Strategy pattern allows a client to choose from a family of algorithms at runtime.
It is used when the client expects to have multiple algorithms and wants to choose one of them at runtime.

Purpose of .NET implementation

You want to have a function that sort objects based on a specific criteria.
You want to let the developer to provide the sort criteria.
You want also allow the sorting behavior (the strategy) to be selected at runtime.
You can use the Strategy pattern to let developer define the sorting criteria and the strategy to be used at runtime.

Example in .NET :

Strategy

Strategy example for Pattern Strategy
using System;
using System.Collections.Generic;

namespace Strategy;
internal class StrategyDemo
{
public static void SortWithDifferentStrategies()
{
List<int> al = new ();
al.Add(102);
al.Add(201);
// Strategy 1: Sorts the list in ascending order.
al.Sort((x, y) => x.CompareTo(y));

for (int i = 0; i < al.Count; i++)
{
Console.WriteLine(al[i]);
}

Console.WriteLine("---------------");

// Strategy 2: Sorts the list in descending order.
al.Sort((y, x) => x.CompareTo(y));
for (int i = 0; i < al.Count; i++)
{
Console.WriteLine(al[i]);
}
Console.WriteLine("---------------");
// Strategy 3: Sorts the list based on the last digit of each number.
al.Sort((x, y) => LastDigit(x).CompareTo(LastDigit(y)));
for (int i = 0; i < al.Count; i++)
{
Console.WriteLine(al[i]);
}

var array = al.FindAll(it => it > 10);


}

static int LastDigit(int x)
{
return x % 10;
}

}


Download source

See Source Code for Microsoft implementation of Strategy

SourceCode Array.Sort

Learn More

C2Wiki
dofactory
DPH
Wikipedia

Homework

Image you want to serialize classes to XML,JSON and CSV.
Implement a strategy that will allow you to choose between XML , JSON and CSV serialization at runtime.