| 1 | package net.gprussell; |
| 2 | |
| 3 | import java.util.HashMap; |
| 4 | import java.util.Map; |
| 5 | |
| 6 | public class State { |
| 7 | public static String STATE1 = "S1"; |
| 8 | public static String STATE2 = "S2"; |
| 9 | public static String STATE3 = "S3"; |
| 10 | public static String STATE4 = "S4"; |
| 11 | |
| 12 | public static String TRANSITION1 = "T1"; |
| 13 | public static String TRANSITION2 = "T2"; |
| 14 | public static String TRANSITION3 = "T3"; |
| 15 | public static String TRANSITION4 = "T4"; |
| 16 | |
| 17 | /* |
| 18 | * Valid transitions |
| 19 | * S1 -> S2 |
| 20 | * S1 -> S3 |
| 21 | * S2 -> S3 |
| 22 | * S3 -> S4 |
| 23 | */ |
| 24 | static Map<String, String> allowed; |
| 25 | static { |
| 26 | allowed = new HashMap<String, String>(); |
| 27 | allowed.put(STATE1 + TRANSITION1, STATE2); |
| 28 | allowed.put(STATE1 + TRANSITION2, STATE3); |
| 29 | allowed.put(STATE2 + TRANSITION3, STATE3); |
| 30 | allowed.put(STATE3 + TRANSITION4, STATE4); |
| 31 | } |
| 32 | |
| 33 | private String currentState; |
| 34 | |
| 35 | public State() { |
| 36 | this.currentState = STATE1; |
| 37 | } |
| 38 | |
| 39 | public State transition(String transition) { |
| 40 | String newState = allowed.get(this.getCurrentState() + transition); |
| 41 | if (newState == null) |
| 42 | throw new RuntimeException("Invalid transition from " + |
| 43 | this.getCurrentState() + " with transition " + transition); |
| 44 | this.setCurrentState(newState); |
| 45 | return this; |
| 46 | } |
| 47 | |
| 48 | public String getCurrentState() { |
| 49 | return currentState; |
| 50 | } |
| 51 | |
| 52 | public void setCurrentState(String currentState) { |
| 53 | this.currentState = currentState; |
| 54 | } |
| 55 | } |