Your task fits well in using the State pattern, below I presented an example code of how the class dependency might look. We split the big switch into several classes, each of which is responsible for processing one state and can transfer the program to other states.
For example, I used the Python language, since it is quite visual, and sketched out several classes similar to the problem I once solved, I also explicitly added methods that are called for states when switching to it and leaving it, sometimes this is useful.
class StateInterface:
def on_enter(self):
...
def work(self):
...
def on_leave(self):
...
class StateOne(StateInterface):
def __init__(self, main_program):
self.main_program = main_program
def on_enter(self):
# do some init
...
def work(self):
# do some work
new_state = StateTwo(self.main_program)
self.main_program.change_state(new_state)
def on_leave(self):
# do some clear
...
class StateTwo(StateInterface):
...
class MainProgram:
def __init__(self, initial_state: StateInterface):
self.current_state = initial_state
def infinite_loop(self):
while not self.stopped:
self.current_state.work()
def change_state(self, new_state: StateInterface):
self.current_state.on_leave()
self.current_state = new_state
self.current_state.on_enter()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…