Skip to content

Commit 60b474d

Browse files
committed
🔧 Adding
Strategy Design Pattern
1 parent cb01719 commit 60b474d

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from abc import ABC, abstractmethod
2+
3+
4+
# ----------- STRATEGY INTERFACE -----------
5+
class RouteStrategy(ABC):
6+
@abstractmethod
7+
def build_route(self, start: str, end: str) -> None:
8+
...
9+
10+
11+
# ----------- CONCRETE STRATEGIES -----------
12+
class DrivingStrategy(RouteStrategy):
13+
def build_route(self, start: str, end: str) -> None:
14+
print(f"🚗 Calculating driving route from {start} to {end} via highways and roads.")
15+
16+
17+
class WalkingStrategy(RouteStrategy):
18+
def build_route(self, start: str, end: str) -> None:
19+
print(f"🚶 Calculating walking route from {start} to {end} via pedestrian paths.")
20+
21+
22+
class PublicTransportStrategy(RouteStrategy):
23+
def build_route(self, start: str, end: str) -> None:
24+
print(f"🚌 Calculating public transport route from {start} to {end} using bus/train schedules.")
25+
26+
27+
# ----------- CONTEXT -----------
28+
class Navigator:
29+
def __init__(self, strategy: RouteStrategy):
30+
self._strategy = strategy
31+
32+
def set_strategy(self, strategy: RouteStrategy) -> None:
33+
self._strategy = strategy
34+
print(f"[Navigator] Strategy changed to: {strategy.__class__.__name__}")
35+
36+
def navigate(self, start: str, end: str) -> None:
37+
print(f"[Navigator] Routing from {start} to {end}...")
38+
self._strategy.build_route(start, end)
39+
40+
41+
# ----------- CLIENT CODE -----------
42+
def main():
43+
# Create context with a default strategy
44+
navigator = Navigator(DrivingStrategy())
45+
46+
# Simulate user selecting different modes
47+
navigator.navigate("Central Park", "Empire State Building")
48+
49+
navigator.set_strategy(WalkingStrategy())
50+
navigator.navigate("Central Park", "Empire State Building")
51+
52+
navigator.set_strategy(PublicTransportStrategy())
53+
navigator.navigate("Central Park", "Empire State Building")
54+
55+
56+
if __name__ == "__main__":
57+
main()

0 commit comments

Comments
 (0)