Strategy - Harsh4999/Design-Patterns GitHub Wiki
Strategy
USE
- Allows us to encapsulate an algo in class. Possible to use varios algo's
- A good indication to use this is when we have different condition for making a calculation for using different approaches
- Usually implemented in an inheritance hierarchy so that we can choose any one implementation and it'll work with our main object/context as the interface is same for all implementations.
UML
- Context: Uses strategy object to perform an operation. It will hold a strategy object inside which will have algo implementation
- Strategy: Interface defining different algo
- Concrete Strategy: Implementation of strategy
Implementation
- Start by creating interface for strategy. Context class provides strategy with all the data that it needs.
- We provide implementation for various algorithms by implementing strategy interface a class per algorithm
- Our context class provides a way to configure it with one of the strategy implementations.
- We can configure in such a way that if client does not give strategy we use default stratedy
- Eg: Comparator