Java FiniteStateMachine Wiki
Simple Finite State Machine in Java
Status: Alpha
Brought to you by:
papajim
The simplest use of this library is to create state transition diagrams. Consider for example, the following workflow of an Agile Product Owner who reviews a story that has just been developed:
Although you can chose any object to represent the states and actions, enum is a natural choice, so they may look something like this:
enum ReviewState { Developed, RequiresChanges, Modified, Approved, Rejected } enum Action { Review, Approve, Modify, Reject }
To create the state transition diagram, you simply instantiate it and add the states:
StateTransitionTable<ReviewState, Action> table = new StateTransitionTable<ReviewState, Action>(); table.addTransition(ReviewState.Developed, Action.Approve, ReviewState.Approved); table.addTransition(ReviewState.Developed, Action.Review, ReviewState.RequiresChanges); table.addTransition(ReviewState.Developed, Action.Reject, ReviewState.Rejected); table.addTransition(ReviewState.RequiresChanges, Action.Modify, ReviewState.Modified); table.addTransition(ReviewState.Modified, Action.Review, ReviewState.RequiresChanges); table.addTransition(ReviewState.Modified, Action.Reject, ReviewState.Rejected); table.addTransition(ReviewState.Modified, Action.Approve, ReviewState.Approved);
The state transition diagram created above can be used to obtain the next valid state given the current state and an action, or validate weather an action is valid for a particular state. Here is a (unit test) example:
assertEquals(ReviewState.Rejected, table.getNextState(ReviewState.Modified, Action.Reject)); try { table.getNextState(ReviewState.Rejected, Action.Approve); } catch (InvalidTransitionException ite) { assertEquals("There is no transition from state Rejected on symbol Approve.", ite.getMessage()); }