|
| 1 | +export interface RouteStrategy { |
| 2 | + buildRoute(origin: string, destination: string): string; |
| 3 | +} |
| 4 | + |
| 5 | +class RoadStrategy implements RouteStrategy { |
| 6 | + buildRoute(origin: string, destination: string): string { |
| 7 | + return `Road route from ${origin} to ${destination}`; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +class WalkingStrategy implements RouteStrategy { |
| 12 | + buildRoute(origin: string, destination: string): string { |
| 13 | + return `Walking route from ${origin} to ${destination}`; |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +class PublicTransportStrategy implements RouteStrategy { |
| 18 | + buildRoute(origin: string, destination: string): string { |
| 19 | + return `Public transport route from ${origin} to ${destination}`; |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +class Navigator { |
| 24 | + private routeStrategy: RouteStrategy; |
| 25 | + |
| 26 | + setRouteStrategy(strategy: RouteStrategy) { |
| 27 | + this.routeStrategy = strategy; |
| 28 | + } |
| 29 | + |
| 30 | + buildRoute(origin: string, destination: string): string { |
| 31 | + if (this.routeStrategy) { |
| 32 | + return this.routeStrategy.buildRoute(origin, destination); |
| 33 | + } else { |
| 34 | + return "No route strategy set."; |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +const navigator = new Navigator(); |
| 40 | + |
| 41 | +navigator.setRouteStrategy(new RoadStrategy()); |
| 42 | +console.log(navigator.buildRoute("City A", "City B")); |
| 43 | + |
| 44 | +navigator.setRouteStrategy(new WalkingStrategy()); |
| 45 | +console.log(navigator.buildRoute("Park X", "Museum Y")); |
| 46 | + |
| 47 | +navigator.setRouteStrategy(new PublicTransportStrategy()); |
| 48 | +console.log(navigator.buildRoute("Station P", "Station Q")); |
0 commit comments