SCXML documents (more generically, UML state chart diagrams) can be used to define stateful behavior of objects, and Commons SCXML enables developers to take this model directly into the corresponding code artifacts. The resulting artifacts tend to be much simpler, embody a useful separation of concerns and are easier to understand and maintain.
Here is a short exercise in modeling and implementing an object with stateful behavior. A stopwatch -- for anyone who may need an introduction -- is used to measure duration, with one button for starting and stopping the watch and another one for pausing the display (also known as "split", where the watch continues to keep time while the display is frozen, to measure, for example, "lap times" in races). Once the watch has been stopped, the start/stop button may be used to reset the display.
Here is the state chart diagram that describes the behavior
of this particular stopwatch:
The SCXML document is then, a simple serialization of the "model" above: stopwatch.xml.
Here is the class that implements the stopwatch behavior, StopWatch.java. The class extends AbstractStateMachine.java, which provides one approach for providing the base functionality needed by classes representing stateful entities. Points to note in the StopWatch class are:
Here is the UI for our demonstration, StopWatchDisplay.java. Points to note here are: