ActionScript 3.0 Design Patterns

(Chris Devlin) #1

360 | Chapter 10: State Pattern


tive Simulationby Jonathan Kaye and David Castillo (Thomson, 2003). While going


back a few generations of Flash, the book is timeless in its concepts and shows some


very smooth device simulations.


State design structure


As one of the design patterns described inDesign Patterns: Elements of Reusable


Object-Oriented Softwareby the Gang of Four, the value of the State design was rec-


ognized beyond the boundaries of those who were primarily interested in state


machines. Closely resembling the Strategy pattern, the State pattern is used when an


application’s behavior depends on changing states at runtime, or has comple xcondi-


tional statements that branch depending on a current state. When the internal states


change, an object alters its behavior when designed using the State pattern.


Figure 10-3 shows the general structure in the class diagram of the State pattern.


Key OOP Concepts Used with the State Pattern


While polymorphism is a fundamental OOP concept, it doesn’t help very much if its


use and purpose are not understood. It’s just one of the many basic concepts in


object-oriented programming that’s used to point to different implementations of


objects in multiple forms. One feature you’ll see in the State design pattern is that the


polymorphism is pretty obvious. This will help you better understand how polymor-


phism can be useful in OO programs.


Looking at the State interface in Example 10-1, you can see the different methods


that become core behaviors for different states. Each state is its own class. However,


as you look at each class, you can see that the behaviors of the same methods take on


different forms—polymorphism hard at work. Just look at each of the state classes,


and there you see all of the same methods but in different forms.


Perhaps most significant is the ability of each state to take care of knowing itself. For


instance, in the following examples, you will see that both the Stop and Play states


(classes) have astartPlay( )method. However, each acts differently in its context.


Moving from a Stop state initiates playing the video. If the same method,startPlay( ),


is fired while the play is in progress, it does nothing. Doing nothing is important some-


times. Let’s say that someone is looking at a video and, for whatever reason, presses


Figure 10-3. State design pattern


Context
Request

State
Handle()

ConcreteStateA
Handle()

ConcreteState
Handle()

state->Handle()
Free download pdf