Strategy design pattern
What is Strategy design pattern?
- It is behavioural design pattern. This pattern is also referred as Policy pattern.
- This pattern lets us define a family of algorithms, put each of them into a separate class, and make their objects interchangeable.
- This pattern is useful to when there are different algorithms to choose at runtime depending upon user selection/context.
- Same behaviour(end result) however different ways to achieve it.
Real world analogy:
- Consider example of project management.
- To achieve this, there are different strategies/methodologies to choose from. However, main behaviour/end goal is better project management.
- There could be various strategies like Scrum, Kanban, Lean,Waterfall and many more.
Example in software/apps development:
- Consider scenario of Payment processing within mobile application.
- We can infer that there is one behaviour payment that needs to be achieved. However, there are multiple ways/payment mechanisms to complete payment.
- For example, payment can be done using CreditCard , DebitCard or any other mobile wallet APIs. Ultimate goal is to pay specific amount in a specified currency.
- Sample code in swift: https://github.com/ParthContractor/StrategyDesignPattern
Benefits:
- More isolated, understandable and readable code.
- Adherence to Open/Closed principle.
- Changing algorithms/strategies at runtime is easy.
Drawbacks:
- There could be possibility of increased distinct strategies over the period of time and apparently cumbersome to handle/manage them all.
- Clients must understand all strategies to properly utilised one over another at runtime.
Comparison with Template method pattern:
- Template method depends upon single algorithm in abstract super class and allowing concrete subclasses to override part of steps.
- However, Strategy design pattern enables selection of algorithm at runtime. Different strategy is applied to object at runtime to achieve its specific behaviour.
Other interesting articles/reference materials:
- https://sourcemaking.com/design_patterns/strategy
- https://refactoring.guru/design-patterns/strategy
- https://en.wikipedia.org/wiki/Strategy_pattern
- https://stackoverflow.com/questions/31608902/polymorphism-vs-strategy-pattern
Summary:
Strategy pattern is useful when you want to decide during run time how you want to run a particular behaviour from set predefined ways.