Skip to content

Instantly share code, notes, and snippets.

@m-manu
Last active November 28, 2016 06:20
Show Gist options
  • Save m-manu/60a6cf865efcd935f18f6bba71a2c6fc to your computer and use it in GitHub Desktop.
Save m-manu/60a6cf865efcd935f18f6bba71a2c6fc to your computer and use it in GitHub Desktop.
State machine with Jackson serialization
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