ActionScript 3.0 Design Patterns

(Chris Devlin) #1

296 | Chapter 8: Observer Pattern


this.news=news;
this.sports=sports;
this.stocks=stocks;
this.entertainment=entertainment;
}

Like the other elements in the Observer design pattern, the structure remains the


same. The single most comple xchange in the application is going to be format. The


output structure is unchanged, but with four different states, you have to format


your output in such a way that all the different states (information categories) are


separated from one another and spelled out.


Who Are You?


In some applications, you may want to know who’s subscribed to your application.


In fact, you may even want to be sure that the same person doesn’t accidentally


attempt to subscribe more than once, especially where all observers have unique


usernames.


So, to get started, we need to begin with theConcreteObserverclass. Using a string


variable, we’ll add a name to each and every subscriber.


//Subscriber's ID
internal var subName:String;

//Constructor Function
function ConcreteObserver(subName:String):void
{
trace(subName + " has subscribed");
this.subName=subName;
}

By adding a username to the constructor function and connecting that name to the


object created, each observer can hold a username. Now,subNameis a property of the


ConcreteObserverclass, and each element of theobserversarray can use the prop-


erty to identify itself.


To be sure that no more than a single observer with the same name can subscribe,


theConcreteSubjectclass’s subscription function must be changed. By placing a con-


ditional statement that makes sure that no two observer names are alike—or the


same observer doesn’t accidentally subscribe twice to the same subject—we can


automatically reject a subscription with a duplicate name.


//Add variable to check for duplicates
private var duplicate:Boolean;

....(more code)

//Subscribe and Prevent Re-subscription
public function subscribeObserver(obserNow:Observer):void
{
Free download pdf