ActionScript 3.0 Design Patterns

(Chris Devlin) #1

364 | Chapter 10: State Pattern


Initially, in lines 6-8, the script instantiates threeStateobjects—one of each of the


two we designed (PlayStateandStopState), and one (state) that acts as a variable to


hold the current state. Because the state machine begins in the Stop state, the state


variable is assigned the Stop state. (This works just like the light switch before you


change it from theoffstate to theon state.)


Next, the two behaviors from the State interface are specified in terms of the current


state’s context (lines 16-23). We’re going to have to add some code to the two state


classes for it to work with the context class, but for now, think of what will happen


in the two different states when those behaviors are executed. For example, in the


Play state, thestartPlay( )method doesn’t do anything, but in the Stop state, it


switches to the Play state.


Finally, add the getter and setter methods (lines 24-40). We need a total of si xmeth-


ods—a set and get function for each of the three state instances. The setters return


nothing and the getters return a State object.


Completing and testing the abstract state machine


To get everything working, we need to revise the state classes to include the refer-


ence to the context—VideoWorks. Save Example 10-3 asStopState.as.


18 state.startPlay( );
19 }
20 public function stopPlay( ):void
21 {
22 state.stopPlay( );
23 }
24 public function setState(state:State):void
25 {
26 trace("A new state is set");
27 this.state=state;
28 }
29 public function getState( ):State
30 {
31 return state;
32 }
33 public function getPlayState( ):State
34 {
35 return this.playState;
36 }
37 public function getStopState( ):State
38 {
39 return this.stopState;
40 }
41 }
42 }
43

Example 10-2. VideoWorks.as (continued)

Free download pdf