Technical Blog

# Strategy Design Pattern

, 14 Aug 2009 CPOL
 Rate this:
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 ). 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.

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
// that would be your calculated  userNumber against user userNumber
public int yourNumber = 0;

// Strategy aggregation
// Algorithm invokes a strategy method
public int Algorithm()
{
return strategy.Play(this);
}
//// Changing strategies
public void SwitchStrategy()
{
strategy = new YourNumberGet();
else
}
}

// Strategy interface
interface IStrategy
{
int Play(Context c);
}
// Strategy 1
{
public int Play(Context c)
{
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
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:

## 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.

## Share

Software Developer (Senior) BMJ
United Kingdom
No Biography provided

 View All Threads First Prev Next
 My vote of 1 nacata1 10-Oct-11 4:48
 Last Visit: 31-Dec-99 19:00     Last Update: 21-Apr-15 5:27 Refresh 1