366 | Chapter 10: State Pattern
To complete the state machine, we need to create the actual interface, and because
the machine has only two states and two behaviors, this is a simple matter. Return-
ing to the original statechart, you can see only two transitions—one to start the play
and one to stop the play. So, all we’ll need are two functions for abstractions of those
two transitions. Save the script in Example 10-5 asState.as:
The transition behaviors are in lines 6 and 7. Later, we’ll be adding more transitional
behaviors as the project grows, but the actual machine is complete. Finally, we need
to create an FLA file with ActionScript that will execute the state machine.
To both test the abstract application and show features of the State design pattern,
the test should invoke theVideoWorksclass and the two states of Play and Stop using
the primary transitions (methods)—startPlay( )andstopPlay( ). In fact, it should
call both states twice. From the Stop state (default initial state), the application
should be transitioned to the Play state. Then, it should do it a second time to make
sure that the state recognizes the new context. The same should be done to transi-
tion back to the Stop state. Save Example 10-6 asTestState.asin the same folder as
the other files:
Example 10-5. State.as
1 package
2 {
3 //State Machine Interface
4 interface State
5 {
6 function startPlay( ):void;
7 function stopPlay( ):void;
8 }
9 }
Example 10-6. TestState.as
1 package
2 {
3 //Test states
4 import flash.display.Sprite;
5 public class TestState extends Sprite
6 {
7 public function TestState( ):void
8 {
9 var test:VideoWorks = new VideoWorks( );
10 test.startPlay( );
11 test.startPlay( );
12 test.stopPlay( );
13 test.stopPlay( );
14 }
15 }
16 }