ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Dynamically Changing States | 311

is sent to all subscribers via the Observer design pattern. Each of the windows show-


ing the results represents different languages understood by the combatants. When a


combatant is knocked out, it is automatically unsubscribed and no longer receives


information, even though it can sustain further hits recorded by the surviving com-


batants. (The Android is invulnerable, and so can keep firing and receiving informa-


tion even if all the others are knocked out.)


TheChangeHandlerclass is divided into several functions. The constructor function


instantiates the concrete subjects and concrete observers. Each of the observers is


given a name (nomDeGuerre) for keeping track of subscribers who are pushed into a


subscriber array (warrior). A second array (battleUpdate) stores the battle names for


each combatant placed in the text fields representing each combatant’s “damage infor-


mation center.” To simulate the different languages receiving the message from the


concrete subject, each combatant has a different font and border color for the text


field representing its information display. ThecreateTextWindow( ) andgetFont( )


functions handle the viewing objects.


All the objects in the Library panel are placed on the stage along with firing and dam-


age information in a rather large function,getParts( ). These visible objects are coor-


dinated with the instances of the concrete observers.


ThesetScore( )method can be invoked by instances of theConcreteSubjectclass.


Whenever, thesetScore( )method is called, the subscribing observers are notified


via thepassOn( )method, which returns the current score through theupdate( )


method. ThekillWarrior( )function invokes theunsubscribeObserver( )method so


that when a spaceship is knocked out of the game, it no longer receives messages.


Example 8-19 is a fairly large class, and you may want to break it down into smaller


classes or abstract some of the functions. However, it’s designed to show off the


ways in which the Observer design pattern can be used in a context where informa-


tion rapidly changes. Save the script asChangeHandler.asin the same folder as the


other files.


Example 8-19. ChangeHandler.as


package
{
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.display.Sprite;


public class ChangeHandler extends Sprite
{
private var eKiller:uint;
private var aKiller:uint;
private var aFlag:Number;
private var aeFlag:Number;

Free download pdf