Strategy Design pattern is used when you are calculation something with different type of methods.
Navigation
In this tutorial we will create a navigation class which finds route between two points with different type of strategies
interface Strategy {
findRoute(A: string, B:string)
}
class NavigatorContext {
strategy: Strategy;
setStrategy(strategy: Strategy) {
this.strategy = strategy
}
findRoute(A, B) {
return this.strategy.findRoute(A, B)
}
}
class WalkingStrategy implements Strategy{
findRoute(A: string, B: string) {
return `Walking path from ${A} to ${B}`
}
}
class CarStrategy implements Strategy {
findRoute(A: string, B: string) {
return `Driving path from ${A} to ${B}`
}
}
we create an interface for strategy then inside navigator context class we have property for strategy so before finding route between two points we will first set the strategy then with calling findRoute in navigator context class, it will call findRoute of strategy class.
let’s see how it works
let walkingStrategy = new WalkingStrategy();
let carStrategy = new CarStrategy();
const navigatorContext = new NavigatorContext;
navigatorContext.setStrategy(walkingStrategy);
let result = navigatorContext.findRoute('Gas Station', 'National Park');
console.log(result);
// Walking path from Gas Station to National Park
navigatorContext.setStrategy(carStrategy);
result = navigatorContext.findRoute('Street 46', 'Mayor building');
console.log(result);
// Driving path from Street 46 to Mayor building
As you see, first we set strategy to be walking then we called findRoute.
With Strategy design pattern you can add new Strategies in the future WITHOUT modifying previous codes (SOLID second principle) .
check source code in github
https://github.com/mrfarhadir/design-patterns/blob/master/Strategy/Navigator/Simple.ts