Introduction and use of Python state mode

1. Introduction to Python state mode

The Python state pattern (State Pattern) is a behavioral design pattern that allows objects to behave differently in different states, thereby avoiding the use of multiple conditional statements in the code. This pattern encapsulates the state in a self-contained object and chooses different behaviors depending on the current state.

In the state pattern, a state is defined as an independent class that contains its own operations in different states. Its main function is to separate state and behavior, provide a higher level of abstraction, and make the code easier to maintain and expand.

advantage:

  1. Make the code more readable and maintainable;
  2. Easy to extend and modify state and behavior;
  3. Putting the state transition logic inside the state class makes it easier to manage.

shortcoming:

  1. May increase the complexity of the code;
  2. Need to use multiple classes to achieve state transition, increasing the number of classes.

Usually used in the following scenarios:

  1. The number of state transitions of the object is large;
  2. The state of an object is far greater than its behavior;
  3. There is complex logic for state transitions.

When using the state pattern, you need to define the state class first, and then refer to the state class in the main object to achieve state transition. In application development, the state pattern is commonly used in game development, vending machines, and traffic lights, among others.

2. Use of state mode

working principle:

  1. The main object holds a reference to the state class;
  2. Define the behavior of the object in the state in the state class instance;
  3. The main object calls the method of the state class, thereby realizing the state transition.

Example 1: Realize the state switching function

In order to explain in more detail how the Python state mode works and how to use it, we can use a simple example to illustrate: Suppose we have a program that can perform different operations according to different commands entered by the user. We can implement this program using the state pattern.

First, we define a state class, which defines the behavior of the program in different states: an abstract state class is defined State, and three specific state classes StartState, RunningState, StopState. In each specific state class, we have implemented the behavior of the program in that state. Note that if the operation in this state is successfully executed, a new state instance can be returned to achieve state transition.

Next, we define a main object that holds a reference to a state class and can perform different operations based on commands entered by the user: a main object named is defined, which initially holds a Programstarting state instance StartState, and methods of that state instance can be called executeto execute different commands.

Finally, we can run the program with the following code:

# 定义抽象类:1个状态类
class State():
    def execute(self, command):
        pass

# 定义具体类:3个具体类
class StartState(State):
    def execute(self, command):
        if command == "run":
            print("Program is already running.")
        else:
            print("Starting program...")
            # 这里可以添加具体的启动程序代码
            return RunningState()
        return self

class RunningState(State):
    def execute(self, command):
        if command == "run":
            print("Program is already running.")
        elif command == "stop":
            print("Stopping program...")
            # 这里可以添加具体的停止程序代码
            return StopState()
        else:
            print("Invalid command.")
        return self

class StopState(State):
    def execute(self, command):
        if command == "run":
            print("Starting program...")
            # 这里可以添加具体的启动程序代码
            return RunningState()
        elif command == "stop":
            print("Program is already stopped.")
        else:
            print("Invalid command.")
        return self


# 定义主对象
class Program():
    def __init__(self):
        self.state = StartState()

    def execute(self, command):
        self.state = self.state.execute(command)

# 创建实例
program = Program()
program.execute("start")
program.execute("run")
program.execute("stop")
program.execute("stop")
program.execute("invalid comm")
program.execute("run")

operation result:

Starting program...
Program is already running.
Stopping program...
Program is already stopped.
Invalid command.
Starting program...

In the above code, we first created a program instance program, and then executed multiple commands, including starting the program, stopping the program, executing invalid commands, and so on. The program performs different operations according to different states, and returns a new state instance according to the operation execution result, thereby realizing state transition.

Through the above examples, we can understand in more detail how the Python state mode works and how to use it.

Example 2: Realize the switching function

The Python state pattern is often used to implement objects with complex state, especially objects whose state is much larger than behavior. For example, an electronic switch can be in one of several states, such as open, closed, or break a circuit. Each state performs the same operation, but the change in state determines the behavior of the object.

In this scenario, we can use the Python state pattern to implement different states of the object. Specifically, we can define an abstract state class and multiple concrete state classes, each of which represents a state of the object and implements all the methods defined in the abstract state class. At the same time, we can also define an object class, maintain a reference to the current state in it, and provide the operation interface of the object externally. Whenever an object performs an operation, the object class will delegate the operation to a specific state class for execution according to the current state.

Here is a simple example that simulates the multiple states of an electronic switch:

In the above example, we first define a Switchclass that maintains the current state of the electronic switch and provides a method to toggle the state. Then we define an abstract state class State, which defines the interface of the switch operation. Finally, we also define two concrete state classes OnStateand OffState, representing the on and off states respectively. In the specific state class, we implement the specific logic of the switch operation, and when appropriate, switch the state to another state.

State mode can be used to simulate the state transitions of electronic switches in the following ways:

# 维护开关状态
class Switch():
    def __init__(self):
        self.state = OffState()

    def change_state(self, state):
        self.state = state

    def switch_on(self):
        self.state.switch_on(self)

    def switch_off(self):
        self.state.switch_off(self)

# 定义抽象状态类, 定义开关接口
class State():
    def switch_on(self, switch):
        pass
    def switch_off(self, switch):
        pass

# 定义具体类:2个开关状态
class OnState(State):
    def switch_off(self, switch):
        print("switching off...")
        switch.change_state(OffState())

class OffState(State):
    def switch_on(self, switch):
        print("switching on...")
        switch.change_state(OnState())

# 创建实例
switch = Switch()
switch.switch_on() # 输出:switching on...
switch.switch_on() # 无任何输出
switch.switch_off()# 输出:switching off...

operation result:

switching on...
switching off...

Through the above code, we can see that in different states, the specific logic executed by the same operation is different. Also, since the number of electronic switch states is relatively limited, we can easily implement specific logic for each state. In this way, we can separate the state and behavior of the object, thus achieving a more flexible and extensible code structure.

Guess you like

Origin blog.csdn.net/songpeiying/article/details/131960461