Turnstile is a simple device which gives you an access if payment is
made and is a very simple to model using a state machine. In its
simplest form there are only two states, LOCKED
and UNLOCKED
. Two
events, COIN
and PUSH
can happen if you try to go through it or
you make a payment.
States.
public enum States {
LOCKED, UNLOCKED
}
Events.
public enum Events {
COIN, PUSH
}
Configuration.
@Configuration @EnableStateMachine static class StateMachineConfig extends EnumStateMachineConfigurerAdapter<States, Events> { @Override public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception { states .withStates() .initial(States.LOCKED) .states(EnumSet.allOf(States.class)); } @Override public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception { transitions .withExternal() .source(States.LOCKED) .target(States.UNLOCKED) .event(Events.COIN) .and() .withExternal() .source(States.UNLOCKED) .target(States.LOCKED) .event(Events.PUSH); } }
You can see how this sample state machine interacts with event by
running turnstile
sample.
$ java -jar spring-statemachine-samples-turnstile-1.2.9.RELEASE.jar sm>sm print +----------------------------------------------------------------+ | SM | +----------------------------------------------------------------+ | | | +----------------+ +----------------+ | | *-->| LOCKED | | UNLOCKED | | | +----------------+ +----------------+ | | +---| entry/ | | entry/ |---+ | | | | exit/ | | exit/ | | | | | | | | | | | | PUSH| | |---COIN-->| | |COIN | | | | | | | | | | | | | | | | | | | | |<--PUSH---| | | | | +-->| | | |<--+ | | | | | | | | +----------------+ +----------------+ | | | +----------------------------------------------------------------+ sm>sm start State changed to LOCKED State machine started sm>sm event COIN State changed to UNLOCKED Event COIN send sm>sm event PUSH State changed to LOCKED Event PUSH send