Skip to main content

Strategy design pattern


Strategy pattern is a behavioral pattern. It is one of the easiest patterns to learn.

From wikipedia
  • A class should be configured with an algorithm instead of implementing an algorithm directly.
  • An algorithm should be selected and exchanged at run time.
Algorithm here is not necessarily a mathematical algorithm.
It is usually defined as a procedure that takes some value as input, performs a finite number of steps and produces some value as output.
Simply a method that does a specific thing.

"Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it."

Image source wikipedia

Let's have a sample,

  • Encapsulate what varies.
  • Favor composition over inheritance.
  • Program to interface, not implementation.