Intent
It enables us to select an algorithm at runtime. So, Instead of directly implementing a single algorithm, run-time instructions are given to the code as to which family of algorithms to use. So, it encapsulates each algorithm and makes them interchangeable.
Problem
Imagine any of the life situations when you have to choose a one thing from several choices in real-time (quickly) so you might travel to another city and you have to choose between travelling using a car, plane, or a taxi -at any sudden time- and the consequently the route of the trip will be different.
This is when the strategy design pattern role comes in, you choose something among many other things in real-time.
Solution
The strategy design pattern suggests taking the class that does one thing in different ways, and out every way of them in a different class.
Pros and Cons
Pros
- We get a better-simplified unit testing because each algorithm has its own class.
- We can swap algorithms to use inside an object at runtime.
- We can introduce new strategies (algorithms) without having to change the context.
Cons
- User must know totally the differences between strategies to be able to select a proper one.
- It increases the number of classes/objects in an application.
Thank you, and goodbye.