ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Minimalist Abstract State Pattern | 363

As you can see, the behaviors (methods) have different implementations in the differ-


ent states. When you add more states, all you need to do is add their transitional


behaviors to the interface and create a new concrete state (class) that implements the


behaviors. Each new behavior needs to be added to the existing state classes.


Managing All Those States: Hardworking Context Class


To manage the states and their transitions, you need some kind of management


object—the state engine for your state machine. In Figure 10-3 the bo xlabeled


“Context” is the abstraction of the state engine. The context manages the different


states that make up the state machine and contain the different states. Figure 10-4


shows a more concrete representation of what needs to be transformed:


Creating a context class


Looking at our example of creating a simple video player, we need a context that will


serve to get and set the different states. So, the next phase will be to look at a class


(object) that does just that. This context class should be saved asVideoWorks.as.


First, take a look at the class in Example 10-2, and then we’ll see what’s going on:


Figure 10-4. State Design Pattern applied to video


Example 10-2. VideoWorks.as


1 package
2 {
3 //Context class
4 class VideoWorks
5 {
6 var playState:State;
7 var stopState:State;
8 var state:State;
9 public function VideoWorks( )
10 {
11 trace("Video Player is On");
12 playState = new PlayState(this);
13 stopState = new StopState(this);
14 state=stopState;
15 }
16 public function startPlay( ):void
17 {

VideoWorks
Request

State
startPlay()
stopPlay()

PlayState
startPlay()
stopPlay()

StopState
startPlay()
stopPlay()

state->Handle()
Free download pdf