状态模式

描述

在状态模式中,类的行为基于其状态而改变。以上的描述可以说非常笼统,举个实例:

  假设某个机器有三个状态:起始状态(startState)、活动状态(playState)和终结状态(stopState),现在我们有个显示器,这个显示器的功能是显示这个机器在不同状态应该有什么活动,而且只能显示一条。那么我们就要首先根据机器的三个状态分别设置它该有的动作,即三个状态时分别对应不同的动作。每当机器切换状态,都会将状态值传入显示器,显示器会根据状态值找到其动作,显示出来。

  所以状态模式就是用一条记录状态的类来记录不同状态下的机器的不同动作并显示。

实例

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

class StartState implements State {
  public void doAction(Context context) {
    System.out.println("In start state");
    context.setState(this);
  }

  public String toString() {
    return "Start State";
  }
}

class StopState implements State {

  public void doAction(Context context) {
    System.out.println("In stop state");
    context.setState(this);
  }

  public String toString() {
    return "Stop State";
  }
}

class PlayState implements State {
  public void doAction(Context context) {
    System.out.println("In play state");
    context.setState(this);  
  }
  public String toString() {
    return "Play State";
  }
}

class Context {
  private State state;

  public Context() {
    state = null;
  }

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

  public State getState() {
    return state;
  }
}

public class Main {
  public static void main(String[] args) {
    Context context = new Context();

    StartState startState = new StartState();
    startState.doAction(context);

    System.out.println(context.getState().toString());

    PlayState playState = new PlayState();
    playState.doAction(context);
    
    StopState stopState = new StopState();
    stopState.doAction(context);

    System.out.println(context.getState().toString());
  }
}

  

代码来源: 特别感谢 w3school Java设计模式之状态模式

原文地址:https://www.cnblogs.com/K-artorias/p/7941175.html