Get up to 80 % extra points for free! More info:

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.

The Strategy design pattern – UML diagram - GOF - Behavioral Patterns

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.


 

All articles in this section
GOF - Behavioral Patterns
Article has been written for you by David Capka Hartinger
Avatar
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.
Activities