The Strategy Design Pattern allows you to change the behavior of an application when given a context. The context is the outer shell the client code calls, and the behavior are defined by the strategy classes. The strategy pattern allows you to decouple the outer context from the internal behaviors.

The ConcreteStrategy class are classes that implements the behaviors. You will have multiple ConcreteStrategy classes where each class implements a behavior.

It has the Algorithm method that implements the behavior.

The Context class defines the situation to use the behaviors.

It has the strategy variable that points to the behavior of the Context.

Let’s see an example. We would like to create a chess game with different levels of difficulty. The computer will respond based on the level of difficulty chosen by the user. The UML for the chess game will be:

The IComputerPlayer interface defines the behaviors supported.

It has the MakeMove method, which makes a move for the computer player.

The EasyComputerPlayer, MediumComputerPlayer, AdvancedComputerPlayer are the different difficulty levels.

It has the MakeMove method that implements the move the computer makes.

The ChessGame class defines the situation to use the computer players.

It has the computerPlayer variable that holds a IComputerPlayer, which can be any level of difficulties.

The benefit of the strategy pattern is it allows you to choose the behavior of the application at runtime. You only need to define the behaviors as strategy classes, and the client code can simply choose any of the classes to exhibit the behavior.

A comparison between the UML of the strategy pattern and the state pattern shows striking similarities. Both pattern defines the behaviors as the concrete classes, and both pattern defines the context in which the behavior runs under. But there are clear differences. The strategy pattern lets the client code choose the behavior it needs, while the state pattern uses the behavior to switch to other behaviors.

Below are the implementation code and the output using our chess game example. Notice that you can switch to different level of difficulties, or behavior, at anytime during the course of the chess game:

Comments and Discussions

I set my filter to artilcles and all I see is this crap on the front page under articles. This is not an article and it is like this guy is post one page at atime from the dictionary. There is nothing new about the nonsense he is posting and in my opinion he is just another spammer.