BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Design Patterns
.NET 1.1+

Strategy Design Pattern

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.

What is the Strategy Pattern?

The strategy pattern is a Gang of Four design pattern. This is a behavioural pattern as it defines a manner for controlling communication between classes or entities. The strategy pattern is used to create an interchangeable family of algorithms from which the required process is chosen at run-time. This allows the behaviour of a program to change dynamically according to configuration details or user preferences. It also increases flexibility by allowing new algorithms to be easily incorporated in the future.

As an example, the strategy pattern could be used within the scoring system of a fictitious game. In the game, players must run around a circuit that includes a series of checkpoints. At each checkpoint, the player must throw projectiles at a target. Points are scored for successful hits and removed for a slow time around the entire circuit. It may be that men, women and children use different scoring systems. In this case, a set of scoring algorithms could be developed and the decision of which to use be made at run-time, according to the sex and age of each competitor.

Implementing the Strategy Pattern

Strategy Design Pattern UML

The UML class diagram above describes an implementation of the strategy design pattern. The items in the diagram are described below:

  • Client. This class is the user of an interchangeable algorithm. The class includes a property to hold one of the strategy classes. This property will be set at run-time according to the algorithm that is required.
  • StrategyBase. This abstract class is the base class for all classes that provide algorithms. In the diagram the class includes a single method. However, there is no reason why a number of properties and methods may not be included. This class may be implemented as an interface if it provides no real functionality for its subclasses.
  • ConcreteStrategy A/B. The concrete strategy classes inherit from the StrategyBase class. Each provides a different algorithm that may be used by the client.

The following shows the basic code of the strategy design pattern implemented using C#. For brevity, the Client class's Strategy property is declared using C# 3.0 automatically implemented property syntax. For earlier versions of the .NET framework, it would be necessary to expand this syntax.

public class Client
{
    public StrategyBase Strategy { get; set; }

    public void CallAlgorithm()
    {
        Console.WriteLine(Strategy.Algorithm());
    }
}


public abstract class StrategyBase
{
    public abstract string Algorithm();
}


public class ConcreteStrategyA : StrategyBase
{
    public override string Algorithm()
    {
        return "Concrete Strategy A";
    }
}


public class ConcreteStrategyB : StrategyBase
{
    public override string Algorithm()
    {
        return "Concrete Strategy B";
    }
}

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);
    }
}
4 May 2009