SMC uses the Java Bean event notification and .Net event raising features to inform listeners when an SMC-generated finite state machine changes state. The following sample code demonstrates how to use this feature in Java, C#, VB.net, Groovy and Scala.
Java Sample
SMC uses Java Beans package for state change
notification. statemap.FSMContext
defines
the addStateChangeListener
and
removeStateChangeListener
methods. Because
the SMC-generated FSMContext
subclass is
privately contained within an application class, it will
be necessary to expose the add, remove methods by
adding these methods to the application class.
Note: Because applications use multiple state
machines and a state change handler may register with
multiple FSMs, I have added the methods
FSMContext.getName()
and
FSMContext.setName(String)
. This name
should be set and used to distinguish between FSMs.
Implement the
java.beans.PropertyChangeListener
interface
and pass that implementation to
AppClass.addStateChangeListener
. When the
AppClass finite state machine changes state, the listener
receives a
java.beans.PropertyChangeEvent
containing:
-
the
FSMContext
instance as the source. - the "State" property name.
-
the previous state
(class
statemap.State
). -
the new state (class
statemap.State
).
Register the StateChangeListener
with the
FSM as follows:
C# Sample
.Net events required listeners to register an event directly with the event-raising object. For SMC, the finite state machine class FSMContext does the event raising. But the context class should be kept private within the application class. The following code shows how to add and remove state change listeners indirectly, leaving the FSM inaccessible.
The StateChangeEventArgs data methods are:
-
FSMName(): returns the FSM's name as a
string
. -
TransitionType(): returns one of the following
string
's: SET, PUSH or POP. - PreviousState(): returns the state which the FSM exited.
- NewState(): returns the state which at the FSM entered.
Note: Because applications use multiple state
machines and a state change handler may register with
multiple FSMs, I have added the property
FSMContext.Name
. This name is placed into
StateChangeEventArgs
to allow ready
identification of which FSM changed state. The default
state name is "FSMContext".
If a class wishes to receive state change events, then it
must implement a method with the following signature.
Note: the method does not have to be named
StateChanged
.
Register the state change handler instance with the FSM as follows:
VB.Net Sample
State change event handlers register indirectly via these application class methods (which you must add to your code).
If a class wishes to receive state change events, then it must implement a method with the following signature.
See the C# sample for more about StateChangeEventArgs.
Register the state change handler with the FSM as follows: