less than 1 minute read

The strategy pattern allows switching out one algorithm or policy for another without modifying the client.

Instead of directly implementing a single algorithm, the code receives runtime instructions specifying which of the group of algorithms to run.

When should you use it ?

  • Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime.
  • Use the pattern when your class has a massive conditional operator that switches between different variants of the same algorithm.

How do you implement it ?

The Strategy pattern suggests that you take a class that does something specific in a lot of different ways and extract all of these algorithms into separate classes called strategies.