Design Pattern: Strategy Pattern

The Strategy Pattern defines a set of algorithms, encapsulates each one and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. – Head First Design Pattern.

This is a Behavioral Design Pattern. This design pattern follows the following design principles:

  • Encapsulate what varies
  • Favor composition over inheritence
  • Program to interfaces, not implementations

Suppose, we are designing a game. The game has a hero. Players can navigate the hero character and explore different levels to find treasures and defeat monsters. The hero equips a weapon and a potion. Over the entire game, players can find different kinds of weapons and potions to enhance the hero. Each type of weapon does a different action. Every potion does magic but the effect of that magic varies with the type of potion used. How do we design the class diagram?

The class diagram might look like this:

Leave a Reply