State Pattern in Flex

Preview:

DESCRIPTION

Presentation by Andy Bulka on the State design pattern with examples in Flex presented to the Melbourne Patterns Group in September 2008

Citation preview

Andy BulkaTechnical DirectorAusthink Softwarewww.austhink.com

State Alter an object's behavior when its state

changes. Put the “state” in a class and delegate to it.

IntentAllow an object to alter its behavior when its

internal state changes. The object will appear to change its class.

State pattern - UMLClient code talks to the “context.Request()”

which behaves differently

So what if you want to add the new "Orange" state? You usually have to modify code in a number of places.

State instances as SingletonsYou often want to have singleton states

rather than recreating each state time and time again, and having to copy across any state attributes each time. Of course by keeping most of the attributes in the context, there is not much data in state to copy between state instance when the state switches.

What States instances can accessOne main issue in state pattern is how do

state instances access attributes in the context. Simplest solution is to have a pointer back from each state object back to the context. Another solution is to completely decouple the state from the context and simply pass the state instance what it needs e.g. as parameters to state methods (as defined in the the state interface)

Who changes the stateSometimes client code drives the changing of the

stateSometimes client code holds the state instances

too, though I prefer to map these to enums and look them up in a dictionary (see singleton issue above)

Often the states themselves or the context (e.g. car) will take on this responsibility. If the states are given the power to set the next state – they will need need access to the context (via a backpointer) so that they can call a method called e.g. SetState().

Flex 3 example

Flex 3 classesImplement dumb

graphic in either flash or mxml

Deep state pattern switching logic is in pure actionscript code

Hook up the gui to the pattern using various techniques

Flash – dumb graphicGraphics

reified as symbols

Symbols given names

Symbols marked as inheriteing from Flex’s mx.flash.UIMovieClip

UML 1Simple version – flash component subclasses

“context”

UML vers2

Re the behaviour - display()Three versions of

implementing the graphic part is shown.

pure mxml (code embedded inside the mxml)

mxml + actionscript class

flash component (dumb)

Flex 3 MXML graphics

End.

AdvertDesign Pattern Courses - for your companyElevate the effectiveness of your entire programming

team - Andy can deliver a design patterns course to you programming team on your company's premises.  Check out the details here.

http://www.atug.com/andypatterns/training_courses.htm

Recommended