在Java中实现状态机可以通过以下几种方法:
- 使用枚举和接口:
public enum State { STATE_A, STATE_B, STATE_C; } public interface StateMachine { void setState(State state); State getState(); void onEntry(State state); void onExit(State state); } public class MyStateMachine implements StateMachine { private State state; @Override public void setState(State state) { this.state = state; onExit(this.state); onEntry(state); } @Override public State getState() { return state; } @Override public void onEntry(State state) { // 处理进入状态的逻辑 } @Override public void onExit(State state) { // 处理退出状态的逻辑 } }
- 使用状态模式:
public interface State { void handle(Context context); } public class StateA implements State { @Override public void handle(Context context) { // 处理StateA的逻辑 context.setState(new StateB()); } } public class StateB implements State { @Override public void handle(Context context) { // 处理StateB的逻辑 context.setState(new StateC()); } } public class StateC implements State { @Override public void handle(Context context) { // 处理StateC的逻辑 context.setState(new StateA()); } } public class Context { private State state; public Context() { state = new StateA(); } public void setState(State state) { this.state = state; } public void request() { state.handle(this); } }
- 使用第三方库,如Apache Commons State或状态机库(如:jsr310-state):
Apache Commons State: https://commons.apache.org/proper/commons-state/
JSR 310 State: https://www.jcp.org/en/jsr/detail?id=310
这些方法都可以实现状态机,你可以根据项目需求选择合适的方法。