Design Patterns: Strategy

The Strategy design pattern belongs to Behavioral family. It helps us to change behavior at runtime. The definition from Gang of Four book is following.

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from client that use it.Gang of Four

When do we have to use it

  • We use Strategy pattern when we need to hide the implementation of an algorithm.
  • When we have many related classes which differ in their behavior providing a way to configure another class with one of many behaviors.
  • Using Strategy we avoid to expose the complexity of an algorithm.
  • If you have many conditionals in front of you, and each one contains different behaviors of a class, then it is time to use Strategy pattern.

How do I use it

The Strategy design pattern is really easy to use. We just need to provide an Interface. This Interface is going to be used creating multiple implementations of different algorithms.
After implementing our algorithms we just need to create a context (Composition) which is going to use our interface gaining access to algorithms.

Example

Supposing that we develop a game, there is a character and has two or many special powers to use.

Let’s start with the interface and its implementations.

Now we are going to create the context class.

Let’s run an example.

Output:

You can download the source code from GitHub.