Click here to Skip to main content
Click here to Skip to main content

Strategy Design Pattern

, 13 Aug 2009
Rate this:
Please Sign up or sign in to vote.
Strategy Design Pattern

Introduction

By definition, Strategy design pattern allows an object to change its behaviour when its internal state changes. The object will appear to change its class. The Strategy design pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The algorithms can also be expressed independently of the data they are using.

A Little About the Past

In my childhood, I used to play a very interesting number game with my Phopho (Aunt Smile | :) ). She used to play that game with me and I could never figure it out how that was possible. In this game, you ask for any number from a person, for example, if the person thinks of a number like 498 then you tell him ok after some calculation answer will be 2496. How cool was that to guess the number even before any calculation. Now then you ask the person for the number again and that could be 764 then you give your number which is 235, then 3rd time you ask from person for number which could be 671 and you give him number which is 328 now if you add these number up 498 +764 +235 +671 + 328 = 2496 and that's the number my Aunt always guessed it before.

In this number game, the only rule is that you can think of any number greater than 2 but if you give any number, then the user has to stick with that length of number so if its 7864 then all numbers will be equal to length 4.

Explanation

Now let's study more about the strategy design pattern to implement this example. The Strategy pattern involves removing an algorithm from its host class and putting it in a separate class. There may be different algorithms (strategies) that are applicable for a given problem. If the algorithms are all kept in the host, messy code with lots of conditional statements will result. The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The algorithms can also be expressed independently of the data they are using.

image

In our example, we have the following classes as form UML Diagram:

  • Strategy = IStrategy
  • Concrete = FinalAnswerGet, YourNumberGet
  • Context = Context

Client will be our Main class.

The client does need to know about the general workings of the various IStrategy implementations and the workings of the algorithms inside the Context. The Context class doesn't know about the different IStrategy implementations, and only knows the IStrategy interface. So in other words, the Context class won't directly reference the IStrategy implementations and IStrategy implementations won't directly reference the context class instance.

// The Context class
class Context
{
    //This could be any userNumber from User. But it must be greater than 9
    public int userNumber = 5;
    // that would be the answer you can show to your user or friend
    public int FinalAnswer = 0;
    // that would be your calculated  userNumber against user userNumber  
    public int yourNumber = 0;
    
    // Strategy aggregation
    IStrategy strategy = new FinalAnswerGet();
    // Algorithm invokes a strategy method
    public int Algorithm()
    {
        return strategy.Play(this);
    }
    //// Changing strategies
    public void SwitchStrategy()
    {
        if (strategy is FinalAnswerGet)
            strategy = new YourNumberGet();
        else
            strategy = new FinalAnswerGet();
    }
}

// Strategy interface
interface IStrategy
{
    int Play(Context c);
}
// Strategy 1
class FinalAnswerGet : IStrategy
{
    public int Play(Context c)
    {
        return c.FinalAnswer = 
	Convert.ToInt32(("2" + Convert.ToString(c.userNumber - 2)));
    }
}

// Strategy 2
class YourNumberGet : IStrategy
{
    public int Play(Context c)
    {
        //gets the length of userNumber
        int length = Convert.ToString(c.userNumber).Length;
        string numbeToMinus = string.Empty;
        for (int i = 0; i < length; i++)
        {
            numbeToMinus = numbeToMinus + "9";
        }
        return c.yourNumber = Math.Abs(c.userNumber - Convert.ToInt32(numbeToMinus));
    }
}

static class Program
{
    static void Main()
    {
        Context context = new Context();
        context.userNumber = 899;
        context.Algorithm();
        Console.WriteLine("User  enter number = {0} \t  my already guessed 
		final answer =  {1}", context.userNumber, context.FinalAnswer);
        context.userNumber = 245;
        Console.WriteLine("User  enter number  2nd time = {0} ", context.userNumber);
        context.SwitchStrategy();
        context.Algorithm();
        Console.WriteLine("Your   number   = {0} ", context.yourNumber);
        context.userNumber = 382;
        Console.WriteLine("User  enter number  3rd time = {0} ", context.userNumber);
        context.Algorithm();
        Console.WriteLine("Your   number   = {0} ", context.yourNumber);
        Console.WriteLine("{0} 899 + 245 + 754 + 382+ 617= 2897 
	AND OFCOURSE I  GUESSED THIS NUMBER BEFORE", Environment.NewLine);
    }
} 

And the output is:

image

Difference between Strategy Design Pattern and State Design Pattern.

Strategy pattern is similar to the State Design Pattern from an architectural point of view but the intent is entirely different. Unlike the State pattern, the Algorithm class doesn't manage state, but represents an algorithm that uses one or more IStrategy implementations. The IStrategy implementation isn't managed by the Algorithm class, but assigned by the client whereas a state usually selects the next state of its context. A state tends to have lots of unrelated methods, so there is little cohesion between the methods of a state. For more details, please read my posting on State Design Pattern.

View this article on my blog.

Your feedback is welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Salmanzz
Software Developer (Senior) BMJ
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 Pinmembernacata110-Oct-11 3:48 
QuestionInitialization in a separate class ? PinmemberRemi BOURGAREL22-Mar-11 4:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 14 Aug 2009
Article Copyright 2009 by Salmanzz
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid