Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.gabrielbauman.gist;
- import java.util.Arrays;
- /**
- * A very simple (but useful) method of getting basic finite state machine behaviour using a Java enum.
- *
- * <code>
- * EnumStateMachine state = NEUTRAL;
- * state = state.transitionTo(FIRST);
- * state.transitionTo(REVERSE); // IllegalStateException
- * </code>
- */
- public enum EnumStateMachine {
- FIRST,
- NEUTRAL,
- REVERSE;
- static {
- NEUTRAL.allowTransitionTo(FIRST, REVERSE);
- FIRST.allowTransitionTo(NEUTRAL);
- REVERSE.allowTransitionTo(NEUTRAL);
- }
- // Everything below this line is boilerplate. It's too bad we don't have "abstract base enums" in Java.
- private EnumStateMachine[] possibleTransitions;
- private void allowTransitionTo(EnumStateMachine... allowableStates) {
- possibleTransitions = allowableStates;
- }
- public boolean canTransitionTo(EnumStateMachine anotherState) {
- return Arrays.stream(possibleTransitions).anyMatch(anotherState::equals);
- }
- public EnumStateMachine transitionTo(EnumStateMachine newState) {
- if (!canTransitionTo(newState))
- throw new IllegalStateException(String.format("Illegal transition: %s -> %s", this, newState));
- return newState;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement