Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created March 28, 2012 18:13
Show Gist options
  • Save gclaramunt/2228937 to your computer and use it in GitHub Desktop.
Save gclaramunt/2228937 to your computer and use it in GitHub Desktop.
Fluent state machine in Java
package statemachine;
public class Event {
final private String label;
public Event(String newLabel) {
label = newLabel;
}
/**
* @return Returns the label.
*/
public String getLabel() {
return label;
}
public String toString() {
return label;
}
}
package statemachine;
public class SampleFSMDef {
public final static State SUBMITTED = new State("Submitted");
public final static State OPEN = new State("Open");
public final static State CANCELLED = new State("Cancelled");
public final static State CLOSED = new State("Closed");
//Events
static class Events {
public final static Event OPEN = new Event("Open");
public final static Event CLOSE = new Event("Close");
public final static Event REOPEN = new Event("Re-Open");
public final static Event CANCEL = new Event("Cancel");
}
static {
new Transition(Events.OPEN).from(SUBMITTED).to(OPEN);
new Transition(Events.CLOSE).from(OPEN).to(CLOSED);
new Transition(Events.REOPEN).from(CLOSED).to(OPEN);
new Transition(Events.CANCEL).from(OPEN).to(CANCELLED);
}
}
package statemachine;
import java.util.HashMap;
import java.util.Map;
public class State {
private final String label;
private final Map<Event, Transition> transitions = new HashMap<Event, Transition>();
//no public access to the constructor, must be in the same package
State(String newLabel) {
this.label = newLabel;
}
void addTransition(Transition t) {
transitions.put(t.getEvent(), t);
}
public State doEvent(Event e) {
return (transitions.get(e)).getDestination();
}
/**
* @return Returns the label.
*/
public String getLabel() {
return label;
}
/**
* @return Returns the transitions.
*/
public Map<Event, Transition> getTransitions() {
return transitions;
}
}
package statemachine;
public class Transition {
private State origin, destination;
private Event event;
public Transition(Event e) {
event = e;
}
public Transition from(State orig) {
origin = orig;
origin.addTransition(this);
return this;
}
public Transition to(State dest) {
destination = dest;
return this;
}
/**
* @return Returns the destination.
*/
public State getDestination() {
return destination;
}
/**
* @return Returns the event.
*/
public Event getEvent() {
return event;
}
/**
* @return Returns the origin.
*/
public State getOrigin() {
return origin;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment