294 | Chapter 8: Observer Pattern
Note that this script programs to the interface to instantiate the different observer
instances, but must program to theConcreteSubjectdirectly to implement it. How-
ever, we could have typed the observers asConcreteObserver, and then used the
instances asObservertypes in the parameters for subscribing. In either case, we
would have been following the dictum of programming to the interface.
Open a new Flash document, and, in the Document class window, type inTestSub,
and then test the application. Your output should appear as the following:
*|*Concrete Subject*|*
=Concrete Observer=
=Concrete Observer=
=Concrete Observer=
Observer 0 Light is on
Observer 1 Light is on
Observer 2 Light is on
Observer 0 Light is off
Observer 1 Light is off
As you can see, a single instance used theConcreteSubjectconstructor and three
used theConcreteObserverconstructor, as indicated by the respectivetrace( )out-
puts. The observer state was first set to “on” and, as expected, the three observer
instances indicated the correct state. Then, a single observer was unsubscribed, and
the state was set to “off.” With two observers now, only two indicated the state.
Example: Adding States and Identifying Users
The minimal Observer design pattern example had only a single state. You might
think that adding additional states may be complicated, but you’ll see that it’s very
easy. One of the key features about design patterns is that they’re flexible, and add-
ing states illustrates this flexibility.
Another issue that can be important in some applications using the Observer pattern
is getting to know the observers. In the minimal example in the previous section, the
observers were identified by their array index, which changes when observers are
removed. However, using a property to identify observers is quite simple as well.
mySub.setLight("on");
mySub.unsubscribeObserver(subObserver);
mySub.setLight("off");
}
}
}
Example 8-9. TestSub.as (continued)