Minimalist Abstract Observer | 291
To illustrate the Observer design pattern in its minimal form, we’ve chosen a light
that can have an “on” or “off” state. In the abstract interface, though, we simply
indicate the data type accepted in the parameter as a string. So the value could be the
range of a dimmer. We’ve got flexibility. The goal in this example is clarity, but the
Observer pattern’supdate( )function can deal with multiple parameters with any
kind of datatype. Later in this chapter, this will be demonstrated.
Concrete Subject
At this stage, we’ve got to put the interfaces to work. The tasks for the
ConcreteSubject class include:
- Establish an array to hold the observers.
- Establish the state property as part of the class—stores the state.
- Set up the details of subscription process tying in theObserversupertype and
observers array. - Work out a process to remove (unsubscribe) elements of the observer array,
using anObserver supertype in the parameter. - Establish a notification process tied to theupdate( )method derived from the
Observer interface.
The notification process requires some kind of setter. This is where a setter function
has a reference to data that changes the state to be broadcast to the observers. In
turn, when the state changes (the setter function is called), the notification function
kicks in. Save the script in Example 8-7 asConcreteSubject.as.
Example 8-7. ConcreteSubject.as
package
{
public class ConcreteSubject implements Subject
{
private var light:String;
private var observers:Array;
function ConcreteSubject ( )
{
trace ("|Concrete Subject|");
observers=new Array( );
}
public function subscribeObserver (obserNow:Observer):void
{
observers.push (obserNow);
}
public function unsubscribeObserver (obserNow:Observer):void
{
for (var ob:int=0; ob<observers.length; ob++)
{
if (observers[ob]==obserNow)