Black Friday Black Friday
Black Friday ultimate sale! Get up to 80 % extra free points! More information here

Strategy

Software design Design patterns GOF Behavioral Patterns 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

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.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
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 College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Observer
Thumbnail
All articles in this section
GOF - Behavioral Patterns
Thumbnail
Next article
Template method
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!