A tutorial on how to implement the State design pattern in Flex 3. We are going to have a traffic light move through several states (red, orange, green). Of course there are other states the traffic light might be in, as well as transitional states (green and orange at the same time), but lets keep things simple!
Alter an object's behavior when its state changes. Put
the “state” in a class and delegate to it.
Allow an object to alter its behavior when its internal
state changes. The object will appear to change its
State pattern - UML
Client code talks to the “context.Request()” which
So what if
to add the
code in a
State instances as Singletons
You 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 access
One 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
Who changes the state
Sometimes client code drives the changing of the state
Sometimes 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().
Design Pattern Courses - for your company
Elevate 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.