10.12.2012 Views

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

ActionScript 3.0 Design Patterns.pdf - VideoTutorials-bg.com

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Example 10-2. VideoWorks.as (continued)<br />

18 state.startPlay( );<br />

19 }<br />

20 public function stopPlay( ):void<br />

21 {<br />

22 state.stopPlay( );<br />

23 }<br />

24 public function setState(state:State):void<br />

25 {<br />

26 trace("A new state is set");<br />

27 this.state=state;<br />

28 }<br />

29 public function getState( ):State<br />

30 {<br />

31 return state;<br />

32 }<br />

33 public function getPlayState( ):State<br />

34 {<br />

35 return this.playState;<br />

36 }<br />

37 public function getStopState( ):State<br />

38 {<br />

39 return this.stopState;<br />

40 }<br />

41 }<br />

42 }<br />

43<br />

Initially, in lines 6-8, the script instantiates three State objects—one of each of the<br />

two we designed (PlayState and StopState), and one (state) that acts as a variable to<br />

hold the current state. Because the state machine begins in the Stop state, the state<br />

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

change it from the off state to the on state.)<br />

Next, the two behaviors from the State interface are specified in terms of the current<br />

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

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

in the two different states when those behaviors are executed. For example, in the<br />

Play state, the startPlay( ) method doesn’t do anything, but in the Stop state, it<br />

switches to the Play state.<br />

Finally, add the getter and setter methods (lines 24-40). We need a total of sixmethods—a<br />

set and get function for each of the three state instances. The setters return<br />

nothing and the getters return a State object.<br />

Completing and testing the abstract state machine<br />

To get everything working, we need to revise the state classes to include the reference<br />

to the context—VideoWorks. Save Example 10-3 as StopState.as.<br />

364 | Chapter 10: State Pattern

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!