State mode (behavior type)

In State Pattern, the behavior of a class changes based on its state. This type of design pattern is a behavioral model.

In the state mode, we create objects that represent various states and a context object whose behavior changes as the state object changes.

Introduction

Intent: Allows the object to change its behavior when the internal state changes, and the object appears to modify its class.

Main solution: The behavior of an object depends on its state (attributes), and its related behavior can be changed according to its state change.

When to use: The code contains a lot of conditional statements related to the state of the object.

How to solve: Abstract all kinds of concrete state classes.

Key code: There is usually only one method in the command mode interface. There are one or more methods in the state mode interface. Moreover, the methods of the status mode implementation class generally return values, or change the value of instance variables. In other words, the state mode is generally related to the state of the object. The methods of the implementation class have different functions, covering the methods in the interface. The state mode is the same as the command mode, and can also be used to eliminate conditional selection statements such as if ... else.

Application examples:  1. When playing basketball, athletes can have normal state, abnormal state and abnormal state. 2. In Zeng Houyi's chimes, 'Clock is an abstract interface', 'Clock A', etc. is a concrete state, and 'Zeng Houyi's chimes' is a specific context.

Advantages:  1. Encapsulate conversion rules. 2. Enumerate the possible states. Before enumerating states, you need to determine the type of state. 3. Put all the behaviors related to a certain state into a class, and you can easily add new states. You only need to change the object state to change the behavior of the object. 4. Allow state transition logic and state objects to be integrated, rather than a huge conditional statement block. 5. You can let multiple environment objects share a state object, thereby reducing the number of objects in the system.

Disadvantages:  1. The use of state mode will inevitably increase the number of system classes and objects. 2. The structure and implementation of the state mode are more complicated. If used improperly, it will lead to confusion of the program structure and code. 3. The support of the "open and close principle" in the state mode is not very good. For the state mode that can switch states, adding a new state class needs to modify the source code responsible for state transition, otherwise it cannot switch to the new state, and modify The behavior of a state class also needs to modify the source code of the corresponding class.

Use scenarios:  1. Scenarios where behavior changes as the state changes. 2. Substitute for conditions and branch statements.

Note: Use state mode when the behavior is constrained by the state, and there are no more than 5 states.


achieve

We will create a  State  interface and  an entity state class that implements the  State interface. Context  is a class with a certain state.

StatePatternDemo , our demo class uses  Context  and state objects to demonstrate the behavior change of Context when the state changes.

First class diagram

 

First create a state machine, which has state object variables used to represent the current state

public class Context {

    //当前状态
    private State state;

    public void setState(State state) {
        this.state = state;
    }

    public State getState() {
        return state;
    }

    //启动
    public void start() {
        getState().start(this);
    }

    //关闭
    public void close() {
        getState().close(this);
    }
}

Create a state interface State

public interface State
{
    public void start(Context context);
    public void close(Context context);
}

 

In creating two state classes, implement the state interface

/**
 * 开机状态
 */
public class StartState implements State {

    public void start(Context context) {
        System.out.println("already start");
    }

    public void close(Context context) {
        context.setState(new CloseState());//注意状态的切换
        System.out.println("close State");
    }
}


/**
 * 关闭状态
 */
public class CloseState implements State {

    public void start(Context context) {
        context.setState(new StartState());//注意状态的切换
        System.out.println("start State");
    }
    public void close(Context context) {
        System.out.println("already close");
    }
}

Start the test below

/**
 * 客户端测试
 */
public class Client {
    public static void main(String... args) {
        Context context = new Context();
        
        // 初始为开始状态
        context.setState(new StartState());
        // 切换为关闭状态
        context.close();
        // 切换为开始状态
        context.start();
        context.start();
    }
}
close State
start State
already start

Process finished with exit code 0

 

Published 138 original articles · praised 34 · 150,000 views

Guess you like

Origin blog.csdn.net/bbj12345678/article/details/105220324