O'Reilly logo

ActionScript 3.0 Design Patterns by Chandima Cumaranatunge, William Sanders

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Minimalist Abstract State Pattern

Using the State design pattern, all the behaviors (methods) for a single state are placed into single objects (concrete states), and all transition behaviors for the application (state machine) are placed into a single interface. Each state object implements the interface in a fashion appropriate for the state. Because of this structure, no conditional statements are required to branch differentially depending on the current state. Rather than writing complex conditional statements, the individual state objects define how the methods are to behave for that state.

For example, with a two-state machine (Play and Stop), the following pseudocode could direct the state behavior to start playing the video, depending on the state machine's current state.

function doPlay():void {
    if(state == Play)
    {
        trace("You're already playing.");
    }
    else if (state == Stop)
    {
        trace("Go to the Play state.");
    }
}

With a couple of states that's not too difficult. However, as you add states, things get more complicated and you find a sea of conditional statements that have to all work in sync. The alternative is to set up "contextual" behavior using a State pattern. For example, the following code in Example 10-1 has two different objects with different implementations of behaviors from an interface:

Example 10-1. State.as

//Interface interface State { function startPlay():void; function stopPlay():void; } //Play State object class PlayState implements State { public function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required