Description
It defines a family of algorithms, encapsulates each one of them and makes them interchangeable. This means that reusability increases while preventing the code from breaking.
When should you use Strategy?
- When many related classes different only in one behavior. This way, you don’t constantly have to implement/write code for every class that uses that specific funtion
- It enables an algorithm’s behavior to be selected at runtime.
Example
Let’s take a look at an example from geeksforgeeks.
They use an example of the game “Street Fighter” where there are 4 types of fighters. They can all use the moves jump(), kick(), roll(), duck() but each of their implementation is different. In this case, you can use an interface to make sure the character has to perform all these moves. What if only a few of the characters can perform break().
The solution to this is that we have to either put it in the interface and implement it in everyclass or write a block of code for it for every character that uses it. Too much work don’t you think?
You can always use the strategy pattern to solve this type of problem.
Steps to create a Strategy Pattern
- Create an interface containing the method/methods that need to be implemented by certain classes
- Create other classes that implements the interface and need to be dynamically called at runtime. These are the classes that contain the different methods of a certain strategy
- Make an instance of the interface
- Using composition, call the methods depending on the situation of the use
Conclusion
You want to use the strategy pattern when a class has only one behavior that is similar to other behaviors in a list and you want to dynamically choose the behavior. Basically, it goes around the overriding every single implementation of a method if the behavior is similar.
References
The video by Derek Banas explains the Strategy Design pattern extremely well and I suggest you check it out after reading the description