Strategy
The Strategy design pattern allows to replace an algorithm with another one at runtime without changing the code. Algorithms are encapsulated as separated modules.
Motivation
We often use custom algorithms in our applications; it can be a way to calculate a discount in an e-shop, a tax calculation method, a way of storing data, a method to validate data, and so on. There may be multiple algorithms for the same thing because of the compatibility with older data or simply because the algorithm depends on the specific situation.
If we want to change the algorithm at runtime, we'd have to implement the
switch
statement or similar branching unless we know Strategy or
similar pattern. That could be quite messy with the growing number of
algorithms, and every new algorithm requires to change the source code.
Sometimes, we'd like an algorithm to be a kind of an encapsulated module that can be easily replaced with another one without the client noticing it. With the Strategy pattern, we can make this change happen even at runtime.
Pattern
Strategy consists of an abstract Strategy
class that defines the
interface for an entire family of algorithms that represent specific strategies.
Instead of the abstract class, it can also be an interface. The algorithms then
inherit from it and implement this interface with their own logic.
An algorithm instance is often passed to Context
through the
constructor to shield it completely from choosing it.
The Strategy pattern is similar to the Bridge pattern, but it is designed for behavior rather than structure.