Strategy pattern is a software design pattern that enables selecting an algorithm at runtime. In this pattern you define a group of algorithms and put each of them into a separate class, and make their objects interchangeable. Instead of implementing a single algorithm directly, code receives runtime instructions as to which in a group of algorithms should be use.
For example, a class that is for validation on incoming data may use the strategy pattern to select a validation algorithm depending on the type of data, the source of the data and so on. These factors are not known until runtime. The validation algorithms (strategies), encapsulated separately from the validating object, may be used by other validating objects in different areas of the system (or even different systems) without code duplication.
Strategy Design Pattern
- Problem: One of the best examples for this pattern is navigation app in your mobile. After choosing your destination the app would ask you about how to navigate. You would like to go there by your car or by bus? You prefer the fastest way or the shortest way?
Each time you choose a new navigation algorithm, the main class of the navigator should change to handle your request.
- Solution: Strategy Design Pattern!!! In strategy design pattern you have a strategy class that does something in different ways and these algorithms are in separate classes which called strategies.
In our example as a navigation app, each navigation algorithm should be in its own class with a single
navigate method. The method get beginning and destination points and returns a collection of route.
Implementing Strategy Design Pattern in Java
Now we know that, we should have one class as a Strategy and two or more strategies which should implement this class.
In our example we have StrategyInterface as strategy and ShortestWay and FastestWay as two implementation of it.
You can find the complete source in my github.