Allows an object to change its behavior when its internal state changes, and the object appears to modify the class to which it belongs. The alias is Objects for States, and state mode is an object behavior mode.

Context: State: abstract State: ConcreteState: ConcreteState

Abstract state class

public interface State {
   public void doAction(Context context);
}
Copy the code

Concrete state class

public class StartState implements State { @Override public void doAction(Context context) { context.setState(this); }}Copy the code
public class StopState implements State { @Override public void doAction(Context context) { context.setState(this); }}Copy the code

The environment class

public class Context { private State state; public Context(){ state = null; } public void setState(State state){ this.state = state; } public State getState(){ return state; }}Copy the code

Call the class

public class Client { public static void main(String[] args) { Context context = new Context(); StartState startState = new StartState(); startState.doAction(context); StopState stopState = new StopState(); stopState.doAction(context); }}Copy the code

Reference blog.csdn.net/liyifan687/…