状态机的使用在各类项目中使用都比较多,设计模式中的状态模式是将状态机的维护抽象出来,并由需要支持改状态机的对象维护起来。
本文给出一个简单的例子:
- State
public abstract class State { protected int type; public abstract void handler(int input); public abstract void showState(); }
- ConcreteState
public class ConcreteState extends State { @Override public void handler(int input) { if(1 == input){ this.type = 2; }else if(2 == input){ this.type = 1; }else{ this.type = 1; } } public void showState(){ System.out.println(this.type); } }
- Context
public class Context { private State state; public Context(State state){ this.state = state; } public void handlerState(int input){ state.handler(input); } public void showState(){ state.showState(); } }
- App 测试类
public class App { public static void main(String[] args) { State state = new ConcreteState(); Context context = new Context(state); context.showState();//输出0 context.handlerState(1); context.showState();//输出2 context.handlerState(2); context.showState();//输出1 } }