State mode can be seen as a way to change the behavior of an object at run time. State mode allows an object to change its behavior when its internal state changes, which feels like the object itself has changed.
- State interface: the state base class, which defines the interface that different states need to execute together.
- ConcreteSate object: a subclass of the State base class. Different states can implement different operations in the subclass interface.
- Context object: the object that the client needs to pay attention to. This object maintains its own specific state object. When the state changes, it changes the state object in the context, but the context object does not need to be changed.
- The behavior of an object depends on the state of the object at run time, avoiding using a lot of conditional judgments to change the code logic.
- In state mode, it's easier to add new behaviors, just define an additional state.
- It improves the aggregation of coding, so that operations belonging to the same state are classified into one class.
- Because the function of state itself is too single, it may create too many state classes, which makes the use and maintenance very troublesome.
- For Context objects, the introduction of each state may need to be updated, and each update may affect the original behavior, making the maintenance of Context objects more difficult.
""" //Take the electric rice cooker for example, it has three states or three functions: cooking, soup and porridge //After specifying the state of the rice cooker, it starts to work in the corresponding mode """ from abc import ABCMeta, abstractmethod class CookState(metaclass=ABCMeta): """State Interface: defines the interface shared by state objects, that is, what to cook""" @abstractmethod def cook(self): pass class CookRice(CookState): """ConcreteSate Object: Cooking""" def cook(self): print('Cooking rice...') class CookSoup(CookState): """ConcreteSate Object: boiling soup""" def cook(self): print('Cooking soup...') class CookPorridge(CookState): """ConcreteSate Object: cooking porridge""" def cook(self): print('Cooking porridge...') class Cooker: """Context Object: electric rice cooker, decide what to cook according to its own state""" def __init__(self): # Define several states or functions of rice cooker self.states = [CookRice(), CookSoup(), CookPorridge()] self.state_index = 0 def switch_state(self): """Switch the status of rice cooker""" if self.state_index == (len(self.states) - 1): self.state_index = 0 else: self.state_index += 1 def start_cook(self): """start-up""" self.states[self.state_index].cook() if __name__ == '__main__': cooker = Cooker() cooker.start_cook() cooker.switch_state() cooker.start_cook()