ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Dynamically Changing States | 303

update functions. The subscribe and unsubscribe functions are the same as previous


Observer designs in this chapter. Save the classes in Example 8-15 and Example 8-16


by their caption names.


Giving More Work to the Concrete Classes


The two classes representing concrete subjects and observers are changed little from


previous examples. TheConcreteSubjectclass still keeps track of who has sub-


scribed and unsubscribed, and sends out notifications of state changes.


TheConcreteObserverclass, though, has taken on another responsibility. When a


newConcreteObserveris created, it makes sense to automatically subscribe her to the


notification process. So instead of making it a two-step process, one to instantiate


and another to subscribe, theConcreteObservernow automatically subscribes new


instances. To do this, only a single line had to be added to the constructor function:


concreteObserver.subscribeObserver(this);

The parameter references the instance being instantiated. At any time, the instance


can unsubscribe or resubscribe by calling the unsubscribe or subscribe functions.


Example 8-17 and Example 8-18 should be saved using the caption names.


Example 8-15. Subject.as


package
{
//Subject Interface
public interface Subject
{
function subscribeObserver(o:Observer):void;
function unsubscribeObserver(o:Observer):void;
function notifyObserver(score:Number,damage:String):void;
}
}


Example 8-16. Observer.as


package
{
//Observer Interface
public interface Observer
{
function update(score:Number,damage:String):void;
}
}

Free download pdf