forked from ls1248659692/python_guide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate_machine.py
More file actions
63 lines (46 loc) · 1.53 KB
/
state_machine.py
File metadata and controls
63 lines (46 loc) · 1.53 KB
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
53
54
55
56
57
58
59
60
61
62
63
class StateMachine(object):
def __init__(self, init_state):
self.current_state = init_state
self.current_state.run()
def step(self, action):
self.current_state = self.current_state.next(action)
self.current_state.run()
class State(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "<State '%s'>" % self.name
def next(self, action):
if (self, action) in mapping:
next_state = mapping[(self, action)]
else:
next_state = self
print("%s + %s => %s" % (self, action, next_state))
return next_state
def run(self):
print(self, "is current state")
class Action(object):
def __init__(self, name):
self.name = name
def __str__(self):
return "<Action '%s'>" % self.name
State.Running = State("Running")
State.Stopped = State("Stopped")
State.Paused = State("Paused")
Action.start = Action("start")
Action.stop = Action("stop")
Action.pause = Action("pause")
Action.resume = Action("resume")
mapping = {
(State.Stopped, Action.start): State.Running,
(State.Running, Action.stop): State.Stopped,
(State.Running, Action.pause): State.Paused,
(State.Paused, Action.resume): State.Running,
(State.Paused, Action.stop): State.Stopped,
}
if __name__ == '__main__':
state_machine = StateMachine(State.Stopped)
state_machine.step(Action.start)
state_machine.step(Action.pause)
state_machine.step(Action.resume)
state_machine.step(Action.stop)