Skip to content

Example 1: A simple switch

Nikolaos Pougounias edited this page Jul 29, 2014 · 7 revisions

Suppose a simple switch that can be either OFF or ON. The initial state is OFF. The event press moves the switch to ON.

The state diagram of a simple switch

This diagram consists of the following elements:

States

  • STATE_OFF
  • STATE_ON

Event

  • EVENT_PRESS

Transition

  • From STATE_OFF to STATE_ON

Let’s define the above elements in Spring's application context.

At first we declare the event.

    <!-- Event -->
    <bean id="eventPress" class="gr.ekt.fsmengine.api.DefaultEvent">
        <property name="name" value="EVENT_PRESS"/>
    </bean>

Then we declare the states.

    <!-- States -->
    <bean id="stateOff" class="gr.ekt.fsmengine.api.DefaultState">
        <property name="stateName" value="STATE_OFF"/>
    </bean>
    
    <bean id="stateOn" class="gr.ekt.fsmengine.api.DefaultState">
        <property name="stateName" value="STATE_ON"/>
    </bean>

Finally, we declare the transition.

    <!-- Transition -->
    <bean id="transition" class="gr.ekt.fsmengine.api.DefaultTransition">
        <property name="fromState" ref="stateOff" />
        <property name="toState" ref="stateOn" />
    </bean>

At this point we should declare that the transition occurs when the press event arrives at the STATE_OFF. This is accomplished by adding the event transition map to the declaration of STATE_OFF.

    <!-- States -->
    <bean id="stateOff" class="gr.ekt.fsmengine.api.DefaultState">
        <property name="stateName" value="STATE_OFF"/>
        <property name="eventTransitionsMap">
            <map>
                <entry key-ref="eventPress" value-ref="transition"/>
            </map>
        </property>
    </bean>

The complete declaration is under conf/context-example1.xml.

Run src/test/java/gr.ekt.fsmengine.example1.Run to see the execution flow.

Executing example 1

Clone this wiki locally