292 | Chapter 8: Observer Pattern
In this implementation, you can see that most of the work is done with composition.
The constructor has a single construct: instantiating an array. (Thetrace( )state-
ments are superfluous and only added so that you can better see the internal work-
ings of the observer structure.) Both the subscribe and unsubscribe functions use
composition with anObserverobject (supertype) in the parameter. The notify func-
tion references theObservermethod,update( ). So instead of seeing subclassed ele-
ments making up the class, you see composition at work.
When you test the program, you will be programming to an interface rather than an
implementation. To make this possible, look at the following line:
public function unsubscribeObserver(obserNow:Observer):void
Whatever observer object is placed in theobserNowparameter is typed as a supertype
(Observer), not as an implementation type. (In the section “Working the Observer,”
the programming to an interface process is explored further.)
Concrete Observer
TheConcreteObserverclass has a far more focused task than theConcreteSubject
class. It stores the state to be observed to maintain perfect consistency among the
subscribing observers. Save the script in Example 8-8 asConcreteObserver.as.
{
observers.splice (ob,1);
break;
}
}
}
public function notifyObserver ( ):void
{
for (var notify in observers)
{
observers[notify].update (light);
trace ("Observer " + notify + " Light is "+light);
}
}
public function setLight (light:String):void
{
this.light=light;
notifyObserver ( );
}
}
}
Example 8-8. ConcreteObserver.as
package
{
//Concrete Observer
Example 8-7. ConcreteSubject.as (continued)