-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.py
53 lines (40 loc) · 1.05 KB
/
state.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from abc import ABC, abstractmethod
# Context
class TrafficLight:
def __init__(self):
self._state = GreenLight()
def change_state(self, state):
self._state = state
def request(self):
self._state.handle()
# State
class LightState(ABC):
@abstractmethod
def handle(self):
pass
# Concrete StateA
class GreenLight(LightState):
def handle(self):
print("Traffic Light is Green. Go!")
# Concrete StateB
class YellowLight(LightState):
def handle(self):
print("Traffic Light is Yellow. Prepare to stop.")
# Concrete StateC
class RedLight(LightState):
def handle(self):
print("Traffic Light is Red. Stop!")
# Client code
def client_code():
traffic_light = TrafficLight()
traffic_light.request()
traffic_light.change_state(YellowLight())
traffic_light.request()
traffic_light.change_state(RedLight())
traffic_light.request()
# Usage
client_code()
## Output
# Traffic Light is Green. Go!
# Traffic Light is Yellow. Prepare to stop.
# Traffic Light is Red. Stop!