Last active
November 28, 2016 06:20
-
-
Save m-manu/60a6cf865efcd935f18f6bba71a2c6fc to your computer and use it in GitHub Desktop.
State machine with Jackson serialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package manu.sandbox.demos; | |
import com.fasterxml.jackson.annotation.JsonValue; | |
import com.google.common.collect.Sets; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Set; | |
/** | |
* State machine with Jackson serialization | |
*/ | |
public enum State { | |
ON, | |
OFF, | |
UNKNOWN; | |
public static final Map<State, Set<State>> allowedTransitions = new HashMap<State, Set<State>>() { | |
{ | |
put(ON, s(OFF, UNKNOWN)); | |
put(UNKNOWN, s(ON)); | |
} | |
}; | |
public static boolean isAllowed(State fromState, State toState) { | |
Set<State> allowedStates = allowedTransitions.get(fromState); | |
return allowedStates == null || allowedStates.isEmpty() || allowedStates.contains(toState); | |
} | |
public static Set<State> nextStates(State fromState) { | |
return allowedTransitions.get(fromState); | |
} | |
private static Set<State> s(State... states) { | |
return Sets.newHashSet(states); | |
} | |
@JsonValue | |
public int value() { | |
return ordinal(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment