-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathstate.py
41 lines (29 loc) · 889 Bytes
/
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
# ------------------------------
# State Design Pattern
# ------------------------------
# Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.
from abc import ABC, abstractmethod
class State(ABC):
def handle_state(self):
pass
class StateA(State):
def handle_state(self):
print('State changed to StateA.')
class StateB(State):
def handle_state(self):
print('State changed to StateB.')
class Context(State):
def __init__(self):
self.state = None
def set_state(self, state):
self.state = state
def handle_state(self):
self.state.handle_state()
context = Context()
stateA = StateA()
context.set_state(stateA)
context.handle_state()
print('-------------------------------------')
stateB = StateB()
context.set_state(stateB)
context.handle_state()