ActionScript 3.0 Design Patterns

(Chris Devlin) #1

290 | Chapter 8: Observer Pattern


this all work right is the use of an array to hold the subscribing observers, and a dis-


tribution method for broadcasting the current state.


Subject Interface


All we need for theSubjectinterface are three methods to take care of the subscrip-


tion and notification work. Because all of the functions in an interface construct are


abstract, we don’t have a lot of detail to address. However, we’ve got to be careful to


be sure that all the necessary parts are in place. Example 8-5 shows the script to be


saved asSubject.as:


In the first two functions, you’ll see evidence ofcomposition. The “o” parameter is an


Observerdatatype, which is a reference to another interface that’ll be built as part of


the Observer design pattern. If you look at the diagram in Figure 8-2, you’ll see an


arrow from the abstractSubjectto the abstractObserver. That reference to the


Observer datatype is part of the process that uses composition rather than


inheritance.


Observer Interface


TheObserverinterface is deceptively simple. The singleupdate( )function is actually


part of the composition between theObserverandSubjectstructures. However, we


see the composition only when we look at the connection between the concrete


observer and subject through theupdate( )supertype in theObserverinterface. Save


the code in Example 8-6as Observer.as:


Example 8-5. Subject.as


package
{
//Subject Interface
public interface Subject
{
function subscribeObserver(o:Observer):void;
function unsubscribeObserver(o:Observer):void;
function notifyObserver( ):void;
}
}


Example 8-6. Observer.as


package
{
//Observer Interface
public interface Observer
{
function update(light:String):void;
}
}

Free download pdf