Skip to content

Instantly share code, notes, and snippets.

@khalidx
Created January 10, 2019 20:14
Show Gist options
  • Save khalidx/c05996c83b3b9ad7e28992eebcd336e2 to your computer and use it in GitHub Desktop.
Save khalidx/c05996c83b3b9ad7e28992eebcd336e2 to your computer and use it in GitHub Desktop.
A simple state machine implementation in Java using just an enum.
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public enum State {
Ready(Event.Deposit, Event.Quit),
Waiting(Event.Select, Event.Refund),
Dispensing(Event.Remove),
Refunding(Event.Refunding),
Exiting(Event.Quiting);
State(Event... event) {
events = Arrays.asList(event);
}
State next(Event event, State current) {
return events.contains(event) ? map.getOrDefault(event, current) : current;
}
final List<Event> events;
final static Map<Event, State> map = new HashMap<>();
static {
map.put(Event.Deposit, State.Waiting);
map.put(Event.Quit, State.Exiting);
map.put(Event.Select, State.Dispensing);
map.put(Event.Refund, State.Refunding);
map.put(Event.Remove, State.Ready);
map.put(Event.Refunding, State.Ready);
}
public static enum Event {
Deposit, Quit, Select, Refund, Remove, Refunding, Quiting
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment