- 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.
fromabcimportABC, abstractmethod
classState(ABC):
defhandle_state(self):
pass
classStateA(State):
defhandle_state(self):
print('State changed to StateA.')
classStateB(State):
defhandle_state(self):
print('State changed to StateB.')
classContext(State):
def__init__(self):
self.state=None
defset_state(self, state):
self.state=state
defhandle_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()