Minimalist Abstract Observer | 293
Theupdate( )function is tied into theConcreteSubjectclass as a parameter. So all
instances of theConcreteObserverare welded to the single source of updating done
by the concrete subject’s notification function.
Working the Observer
Now we can examine how all the parts work together. In the script that implements
the program, we need to create instances of both the ConcreteSubject and
ConcreteObserver classes. Then, we will need to subscribe observers to the
ConcreteSubjectinstances. Also, just to be sure that everything’s working correctly,
we should unsubscribe at least one observer. In order to test the overall functional-
ity, we need to change the state we’re observing using thesetLight( )method to dif-
ferent values. Only those observer instances subscribed should be able to see the
changes. By first subscribing observers, and then unsubscribing at least one, we
should be able to see if everything’s working as expected. Example 8-9 implements
the Observer design pattern. Save the code asTestSub.as.
class ConcreteObserver implements Observer
{
private var light:String;
function ConcreteObserver( )
{
trace("=Concrete Observer=");
}
public function update(light:String):void
{
this.light=light;
}
}
}
Example 8-9. TestSub.as
package
{
import flash.display.Sprite;
public class TestSub extends Sprite
{
public function TestSub( )
{
var mySub:ConcreteSubject=new ConcreteSubject( );
var subObserver:Observer=new ConcreteObserver( );
var subObserver2:Observer=new ConcreteObserver( );
var subObserver3:Observer=new ConcreteObserver( );
mySub.subscribeObserver(subObserver);
//The subObserver is passed as an instance of Observer
supertype
mySub.subscribeObserver(subObserver2);
mySub.subscribeObserver(subObserver3);
Example 8-8. ConcreteObserver.as (continued)