ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Example: Adding States and Identifying Users | 295

Multiple States


To understand multiple states, just imagine a daily newspaper that has several differ-


ent sections. For example, an abbreviated list might include the following topic areas


that regularly need to be changed:



  • News

  • Sports

  • Stocks

  • Entertainment


All these areas can be represented asStringdata, but for the sake of type variety, we


will make Stocks aNumbertype. In the minimalist example, the initial placement of


the state property is in theupdate( )parameter. To have additional property states,


all we need to do is add more properties. So, in the Observer interface, we’d just


need to change theupdate( ) function to the following:


function update(news:String,sports:String,stocks:Number,entertainment:
String):void;

That was easy. As you can see, different data types are not problematic at all.


Next, the concrete subject needs to store the states, and so each state needs a variable


declaration that can be used for maintaining the current state. The setter function also


needs to deal with each of the four states, and so it too needs to be expanded.


public function setType(news:String,sports:String,stocks:Number,
entertainment:String)
{
this.news=news;
this.sports=sports;
this.stocks=stocks;
this.entertainment=entertainment;
notifyObserver( );
}

Note that thesetType( )function is structurally identical to thesetLight( )function in


the light example. All that’s changed is the number of parameters and variables stored.


Finally, in the concrete subject, we need to change the number of parameters in the


update( ) function that sends out the state change information:


this.observers[notify].update(news,sports,stocks,entertainment);

Again, you can see that no structure has changed—just the number of parameters.


Next, in the concrete observer class, all the changes are to the number of variables


and nothing in the structure. So, instead of establishing a single variable, four are


declared. The keyupdate( ) function is changed to:


public function update(news:String,sports:String,stocks:Number,
entertainment:String):void
{
Free download pdf