ActionScript 3.0 Design Patterns

(Chris Devlin) #1

362 | Chapter 10: State Pattern


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 startPlay( ):void
{
trace("You're already playing");
}
public function stopPlay( ):void
{
trace("Go to the Stop state.");
}
}
//Stop State object
class StopState implements State
{
public function startPlay( ):void
{
trace("Go to the Play state.");
}
public function stopPlay( ):void
{
trace("You're already stopped");
}
}

Free download pdf