ActionScript 3.0 Design Patterns

(Chris Devlin) #1

302 | Chapter 8: Observer Pattern


Whoaa!, the stock market is at 2987.98 and The Bad Bug is showing
at the Bijou.
Curly sees that Memory Prices Down is interesting, and learns that Game
Rained Out.
Whoaa!, the stock market is at 2987.98 and The Bad Bug is showing
at the Bijou.

As each subscription is made, you can see the observer’s name and the fact that he


has subscribed. You can see that all four subscribers see identically formatted data.


The formatting is the same because all the formatting is placed in the


ConcreteSubjectclass. However, that’s easy enough to change simply by removing all


of the formatting and sending raw data. The Observer design pattern makes sure that


whatever information’s sent to the subscribing observers is identical as far as the


state conditions are concerned, but really doesn’t care about the formatting. The


data can be taken and reformatted for any purpose by the observers. It just has to be


the same data.


Using theunsubscribeObservermethod, selected observers are removed from the


subscription list using the line:


bigNews.unsubscribeObserver(ConcreteObserver instance);

As you can see,shempandlarryare unsubscribed between the first and second out-


puts using this method.


Dynamically Changing States


Up to this point, all the Observer patterns’ testing has been done by static assign-


ments of values to the state setters. The purpose was to see how the structure of the


pattern works, but for most practical applications using Flash and ActionScript 3.0,


we should look at something where the state values are rapidly changing, and new


updates have to be sent almost constantly.


To see how rapidly changing data can be sent to a single source, and then dis-


patched to multiple observers, this next application depicts an action game with


three combatants. Two are made up of spaceships with a missile or torpedo and a


space station that shoots a beam at the spaceships. There’s really nothing much you


can do with the game other than fire from the two spaceships and space station, and


watch the two spaceships get destroyed, but it serves to illustrate how all of the hits


are generated by the action on the stage and broadcast to the different combatants.


When a combatant is knocked out of play, he’s no longer subscribed and all that is


visible is the last message before destruction.


Recording a Space Battle


In setting up this particular Observer application, theSubjectandObserverinter-


faces contain only Number and String parameters in the observer notification and

Free download pdf