Andaikan kita mempunyai dua keadaan
Peralihan keadaan ini sangat mudah, mari kita cuba laksanakannya dalam java
Struktur program adalah seperti berikut
Mari kita perkenalkan dahulu representasi status
public class StateTransaction { // 当前状态 private StateEnum currentState; // 相对应动作 private ActionEnum action; // 下一个状态 private StateEnum nextState; // 相应事件 private Event event; public StateTransaction() { } public StateEnum getCurrentState() { return currentState; } public ActionEnum getAction() { return action; } public StateEnum getNextState() { return nextState; } public Event getEvent() { return event; } // 链式初始化对象 public StateTransaction source(StateEnum state) { currentState = state; return this; } public StateTransaction when(ActionEnum action) { this.action = action; return this; } public StateTransaction target(StateEnum state) { nextState = state; return this; } public StateTransaction how(Event event) { this.event = event; return this; } }
Seperti yang anda lihat, terdapat empat kuantiti yang mewakili status, iaitu:
currentState: mewakili keadaan semasa
tindakan: mewakili tindakan yang sepadan
nextState: mewakili keadaan seterusnya
< . dipindahkan ke status nextState, dan akan mencetuskan respons kepada acara acara.public interface Event { public String handle(); }
public class PlayBasketballEvent implements Event{ @Override public String handle() { System.out.println("开始打篮球"); return "开始打篮球"; } }
public class SingDanceRapEvent implements Event{ @Override public String handle() { System.out.println("开始唱,跳,rap"); return "开始唱,跳,rap"; } }
public enum StateEnum { // 打篮球 PLAY_BASKETBALL, // 唱跳rap SING_DANCE_RAP } public enum ActionEnum { // 音乐起 MUSIC_ON, // 音乐结束 MUSIC_OFF }
public class StateMachine { // 存储状态信息 private List<StateTransaction> stateTransactionList; // 记录当前状态 private StateEnum currentState; public StateMachine(StateEnum state) { currentState = state; stateTransactionList = new ArrayList<>(); } // 添加一条状态信息 public StateTransaction addone() { StateTransaction stateTransaction = new StateTransaction(); stateTransactionList.add(stateTransaction); return stateTransaction; } // 进行状态转移 public StateTransaction execute(ActionEnum action) { for(int i=0; i<stateTransactionList.size(); i++) { if(currentState==stateTransactionList.get(i).getCurrentState() && action==stateTransactionList.get(i).getAction()) { stateTransactionList.get(i).getEvent().handle(); currentState = stateTransactionList.get(i).getNextState(); return stateTransactionList.get(i); } } return null; } }
Atas ialah kandungan terperinci Bagaimana untuk melaksanakan mesin keadaan Java. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!