Strategy Pattern

The Strategy Pattern define a family of algorithms, encapsulates each of them and makes them interchangeable with each other.

Allows the algorithm to vary independently to those who use it.

It is recommended to use this pattern when in the same program we should provide different behavioral alternatives, allowing through independent classes, to encapsulate the different strategies.

The different components of this pattern are:

  1. Strategy interface: will be that interface that defines the name of the method or methods that will make up the strategy.

  2. Concrete Strategy Classes: all those classes that implement the Strategy interface giving shape to the algorithm.

  3. Context: element where the strategy will be developed.

The UML diagram of the implementation of this pattern will be:


As we can see, the Game class would be the generic strategy.

  • Game: Interface in which we define a method that will allow us to play any of these 3 table games.

Now we will develop 3 classes to implement the different ways of playing each existing table game in our application:

  1. Chess: Strategy that would define how to play chess

  2. Parcheesi: Strategy that would define how to play the Parcheesi

  3. Draughts: Strategy that would be define how to play the Draughts

Consequences of the Strategy pattern:

  • It allows to extract a common factor of the functionality of the algorithms

  • Provides an alternative to static inheritance

  • Helps eliminate conditional statements

  • It offers different options for implementing the
    same behavior

I hope you find it very helpful.