Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. package com.gabrielbauman.gist;
  2.  
  3. import java.util.Arrays;
  4.  
  5. /**
  6. * A very simple (but useful) method of getting basic finite state machine behaviour using a Java enum.
  7. *
  8. * <code>
  9. * EnumStateMachine state = NEUTRAL;
  10. * state = state.transitionTo(FIRST);
  11. * state.transitionTo(REVERSE); // IllegalStateException
  12. * </code>
  13. */
  14. public enum EnumStateMachine {
  15.  
  16. FIRST,
  17. NEUTRAL,
  18. REVERSE;
  19.  
  20. static {
  21. NEUTRAL.allowTransitionTo(FIRST, REVERSE);
  22. FIRST.allowTransitionTo(NEUTRAL);
  23. REVERSE.allowTransitionTo(NEUTRAL);
  24. }
  25.  
  26. // Everything below this line is boilerplate. It's too bad we don't have "abstract base enums" in Java.
  27.  
  28. private EnumStateMachine[] possibleTransitions;
  29.  
  30. private void allowTransitionTo(EnumStateMachine... allowableStates) {
  31. possibleTransitions = allowableStates;
  32. }
  33.  
  34. public boolean canTransitionTo(EnumStateMachine anotherState) {
  35. return Arrays.stream(possibleTransitions).anyMatch(anotherState::equals);
  36. }
  37.  
  38. public EnumStateMachine transitionTo(EnumStateMachine newState) {
  39. if (!canTransitionTo(newState))
  40. throw new IllegalStateException(String.format("Illegal transition: %s -> %s", this, newState));
  41. return newState;
  42. }
  43.  
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement