ActionScript 3.0 Design Patterns

(Chris Devlin) #1

358 | Chapter 10: State Pattern


One application where the state pattern’s popular is device simulation. Devices that


change an object’s state are subject to change as the states change. The volume knob


on a radio changes the sound’s volume state. More comple xsimulated devices


include a music sound mixer board where simulated sliders change different states to


affect the overall object (sound mixer) and the resulting sound. A Flash video player


has several states to manage: play, record, append, pause and stop. Each state in the


video player behaves according to the state of the other states as well as its own state.


The State Model


To understand and appreciate the value of the State design pattern, we need to


understand something aboutState Machines. A State Machine is the general model of


states you would be using in an application with the State design pattern. So if a


video player application is designed around key states, the application would be the


state machine. We can also refer to state engines that run the state machines. (Think


of your automobile’s blueprints as a state machine, and the actual car as the state


engine.) The programming we use to move from one state to another is the state


engine. The state engine data structure defines mechanisms for handling messages


and managing contexts.


Rather than beginning with the usual diagrams associated with design patterns,


we’re going to start with astatechart. At its most basic level, a statechart is an illus-


tration of an application’s states and transitions, and as such is a model for the state


machine and engine. Taking a simple video player application, we can see the Play


and Stop states. When the application first runs, the application enters the Stop state


and can only transition to the Play state. Figure 10-1 shows a statechart depicting


this condition.


The illustration is computer-drawn. The idea when sketching state-
charts is to start with a rough idea, and then refine the idea with
sketches. You’ll find that the process goes quicker using hand sketches
with a pencil and scratch paper instead of a drawing program.

The line going from a black dot to the Stop state shows the Application-Not-Run-


ning state, but we’ll assume that the starting point is with the application running in


the Stop state. This could be illustrated in a hierarchical state with Application


Figure 10-1. Simple statechart showing states


Stop Play

start

stop
Free download pdf