Strategy
The strategy pattern
The strategy pattern is a behavioral pattern and is a very simple pattern. Essentially, we choose an object based on some strategy.Without further ado lets start with an example of the strategy abstraction:
abstract class GamePlan {
public virtual void Scheme() {
Console.WriteLine("{0} is scheming.", this.GetType().Name);
}
}
We then have a class that has to use our strategy:
public virtual void Scheme() {
Console.WriteLine("{0} is scheming.", this.GetType().Name);
}
}
class Scenario {
private GamePlan gamePlan;
private Scenario(GamePlan gamePlan) {
this.gamePlan = gamePlan;
}
public static Scenario CreateScenarioWithGamePlan(GamePlan gamePlan) {
return new Scenario(gamePlan);
}
public void Maneuver() {
gamePlan.Scheme();
}
}
Pretty basic stuff, we can inject out strategy at runtime.private GamePlan gamePlan;
private Scenario(GamePlan gamePlan) {
this.gamePlan = gamePlan;
}
public static Scenario CreateScenarioWithGamePlan(GamePlan gamePlan) {
return new Scenario(gamePlan);
}
public void Maneuver() {
gamePlan.Scheme();
}
}
I've constructed a few simple classes that would enact a specific strategy:
class SimpleTactics : GamePlan {
}
class FancyTactics : GamePlan {
}
class ComplexTactics : GamePlan {
public override void Scheme() {
base.Scheme();
Console.WriteLine("Adding more for ComplexTactics...");
}
}
Then a very simple test program, now I've not introduced any criteria for our strategy changes but imagine some
illustrious decision making engine:
}
class FancyTactics : GamePlan {
}
class ComplexTactics : GamePlan {
public override void Scheme() {
base.Scheme();
Console.WriteLine("Adding more for ComplexTactics...");
}
}
static void Main(string[] args) {
GamePlan simpleTactics = new SimpleTactics();
GamePlan fancyTactics = new FancyTactics();
GamePlan complexTactics = new ComplexTactics();
Scenario scenario = Scenario.CreateScenarioWithGamePlan(simpleTactics);
scenario.Maneuver();
scenario = Scenario.CreateScenarioWithGamePlan(fancyTactics);
scenario.Maneuver();
scenario = Scenario.CreateScenarioWithGamePlan(complexTactics);
scenario.Maneuver();
Console.ReadKey();
}
And then the output is predictably:
GamePlan simpleTactics = new SimpleTactics();
GamePlan fancyTactics = new FancyTactics();
GamePlan complexTactics = new ComplexTactics();
Scenario scenario = Scenario.CreateScenarioWithGamePlan(simpleTactics);
scenario.Maneuver();
scenario = Scenario.CreateScenarioWithGamePlan(fancyTactics);
scenario.Maneuver();
scenario = Scenario.CreateScenarioWithGamePlan(complexTactics);
scenario.Maneuver();
Console.ReadKey();
}
SimpleTactics is scheming.
FancyTactics is scheming.
ComplexTactics is scheming.
Adding more for ComplexTactics...
FancyTactics is scheming.
ComplexTactics is scheming.
Adding more for ComplexTactics...
Summary
That's the strategy pattern, I think it's one of the simpler patterns and is used ubiquitously, but the developer that used the pattern may not have known that it was used.