Java Design Patterns----------State Patterns

1 Introduction

The idea of ​​the state pattern is to encapsulate the state and the transition rules between states ( state machine ) and the characteristic behavior corresponding to the state into an object, and use the object to assemble the environment class (context), so that the context can be automatically changed when the state is switched. Some behavior (the behavior of the context mainly depends on the behavior of the state).

Implementation: There are generally three roles in the state pattern: abstract state interface, concrete state class and context class.

  • Abstract State Interface: A generic method for defining state classes in an abstract interface
  • Concrete state class: The method that implements the state interface, which needs to contain the state transition relationship and the corresponding execution logic, and update the new state to the context.
  • Context class (context): depends on the state class, and executes the corresponding logic according to the state switch represented by the state class.

Application Scenario: There are some restrictions on the state mode.

  • State classes are limited because all state classes need to be enumerated to create.
  • The state switching is in the form of a single/double linked list or a circular single/double linked list (if it is a tree, it is inconvenient to determine what the next state is).
  • Each state corresponds to a different execution logic.

There are many scenarios of this single/double chain state in life. For example, the new policy of the State Council is passed down from level to level, reaching different levels to represent a state, then the execution logic corresponding to each state is also different (provincial people's congress and city people's congress). For example, the level title in the game is one-way (or two-way) change, and the activity permissions of each level are different. For example, the status of an order in shopping also changes in one direction. Different order statuses will lead to different information prompted to users.

2. Case

2.1. Background

Taking the status of an order during the shopping process as an example, let's talk about the status mode. During the shopping process, the order generally has these states, pending payment, pending delivery, pending evaluation, and completed. In different states, the prompt information the user sees is different (the behavior is different).

2.2. Implementation

image description
abstract state interface

public interface OrderState
{
    void action(Context context);
    void doPrint();
}

Concrete state class

public class PendingPaymentState implements OrderState
{
    @Override
    public void action(Context context)
    {
        context.setOrderState(new PendingDeliveryOrder());
    }

    @Override
    public void doPrint()
    {
        System.out.println("Get the money!");
    }
}
public class PendingDeliveryOrder implements OrderState
{
    @Override
    public void action(Context context)
    {
        context.setOrderState(new PendingEvaluation());
    }

    @Override public void doPrint()
    {
        System.out.println("Waiting for delivery!");
    }
}
public class PendingEvaluation implements OrderState
{
    @Override
    public void action(Context context)
    {
        context.setOrderState(new CompletedOrder());
    }

    @Override public void doPrint()
    {
        System.out.println("Hurry up and comment!");
    }
}
public class CompletedOrder implements OrderState
{
    @Override
    public void action(Context context)
    {
        context.setOrderState(null);
    }

    @Override public void doPrint()
    {
        System.out.println("Order completed!");
    }
}

Environment class

public class Context
{
    private OrderState orderState;

    public Context(OrderState orderState)
    {

        this.orderState = orderState;
    }

    public void setOrderState(OrderState orderState)
    {
        this.orderState = orderState;
    }

    public void action()
    {
        this.orderState.action(this);
    }

    public void printInfo()
    {
        if (this.orderState != null)
        {
            this.orderState.doPrint();
        }
    }
}

validator

public class Demo
{
    public static void main(String[] args)
    {
        OrderState orderState = new PendingPaymentState();
        Context context = new Context(orderState);
        context.printInfo();

        //User pays
        context.action();
        context.printInfo();

        //user sign
        context.action();
        context.printInfo();

        //User evaluation
        context.action();
        context.printInfo();
    }
}

output result

Get your money now!
Waiting for delivery!
Rate it now!
Order is complete!

Process finished with exit code 0

3. Summary

The core of the state pattern is to encapsulate the state, state switching rules and corresponding execution logic into a class, so that the environment class can be called elegantly and uniformly.

Advantages: The state switching rules and execution logic are encapsulated into a separate class, and the environment class can be processed uniformly and conveniently.

Disadvantage: When there are more states, more state classes will be generated. The open-closed principle cannot be well supported. When a new state class is added, the adjacent state class needs to be modified (equivalent to state machine insertion).

The structure of the state pattern and the strategy pattern is relatively similar, but there is a big difference between the two. Strategy mode models algorithms or strategies, and does not involve switching between algorithms. The state mode is to model the state, involving switching between states, which is actually the model of the state machine , and each state corresponds to different processing logic.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324462277&siteId=291194637