BlackWaspTM
Design Patterns
.NET 1.1+

Strategy Design Pattern (2)

The strategy pattern is a design pattern that allows a set of similar algorithms to be defined and encapsulated in their own classes. The algorithm to be used for a particular purpose may then be selected at run-time according to your requirements.

Example Strategy

In this section we will create a simple example of the application of the strategy design pattern. This example will implement the scoring system described earlier in the article. We will create a Scoreboard class that outputs the score for a person playing a game with the score base upon the number of targets hit and the time taken to complete the course. The calculation of the score will use one of three sets of rules according to the type of player. The scoring rules are as follows:

  • Men. One hundred points will be awarded for every target hit. Five points will be subtracted for each second of time taken.
  • Women. One hundred points will be awarded for every target hit. Four points will be subtracted for each second of time taken.
  • Children. Two hundred points will be awarded for every target hit. Two points will be subtracted for each second of time taken.

The code for the scoreboard and the scoring algorithms is as follows:

public class Scoreboard
{
    public ScoringAlgorithmBase Scoring { get; set; }

    public void ShowScore(int hits, TimeSpan time)
    {
        Console.WriteLine(Scoring.CalculateScore(hits, time));
    }
}


public abstract class ScoringAlgorithmBase
{
    public abstract int CalculateScore(int hits, TimeSpan time);
}


public class MensScoringAlgorithm : ScoringAlgorithmBase
{
    public override int CalculateScore(int hits, TimeSpan time)
    {
        return (hits * 100) - ((int)time.TotalSeconds / 5);
    }
}


public class WomensScoringAlgorithm : ScoringAlgorithmBase
{
    public override int CalculateScore(int hits, TimeSpan time)
    {
        return (hits * 100) - ((int)time.TotalSeconds / 4);
    }
}


public class ChildrensScoringAlgorithm : ScoringAlgorithmBase
{
    public override int CalculateScore(int hits, TimeSpan time)
    {
        return (hits * 200) - ((int)time.TotalSeconds / 2);
    }
}

Testing the Strategy

To test the strategy example classes we can use a console application containing all of the above code. Add the code shown below to the Main method and then execute the program. The test code creates a new scoreboard and displays three scores. Each score using a different scoring algorithm.

Scoreboard board = new Scoreboard();

Console.Write("Man ");
board.Scoring = new MensScoringAlgorithm();
board.ShowScore(8, new TimeSpan(0, 1, 31));

Console.Write("Woman ");
board.Scoring = new WomensScoringAlgorithm();
board.ShowScore(9, new TimeSpan(0, 1, 49));

Console.Write("Child ");
board.Scoring = new ChildrensScoringAlgorithm();
board.ShowScore(5, new TimeSpan(0, 3, 2));

/* OUTPUT

Man 782
Woman 873
Child 909

*/
4 May 2009