状态模式

描述

代码实现示例

class Test{
  public void main(String[] args){
    //初始化状态
    Context context = new Context();
    //切换状态
    context.handle();
    //..
    //切换状态
    context.handle();
  }
}


//抽象状态类
abstract class State {
    public abstract void handle(Context context);
}


//环境类
class Context {
private State state;
//定义环境类的初始状态
public Context() {this.state = new Begin();}
//设置新状态
public void setState(State state) {this.state = state;}
//读取状态
public State getState() {return (state);}
//对请求做处理
public void handle() {state.handle(this);}
}

//具体状态Begin类
class Begin extends State {
    public void handle(Context context) {
        System.out.println("当前状态是 Begin.");
        //执行完该状态后,需要自动切换到下一个状态
        context.setState(new Finish());
    }
}
//具体状态Finish类
class Finish extends State {
    public void handle(Context context) {
        System.out.println("当前状态是 Finish.");
        //执行完该状态后,需要自动切换到下一个状态
        context.setState(new Begin());
    }
}

实际应用场景

FAQ

Last Updated:
Contributors: dongyz8