ActionScript 3.0 Design Patterns

(Chris Devlin) #1
Key OOP Concepts Used with the Observer Pattern | 287

Open a new Flash document file, and, in the Class Document window, type inMain.


When you test the application, all you’re going to see is:


Zaaaapp!!!
Ka Boom!!!

The first trace( )output is what’s returned when an Alien instance calls the


useWeapon( )method, and the second for theEarthlingdoing the same thing. To see


the difference between programming to an implementation instead of an interface,


look at the following lines that are part of theMain.as script:


//Program to implementation
var alien:Alien=new Alien( );
alien.useWeapon( );

//Program to interface
var spaceWarrior:SpaceWarrior=new Earthling( );
spaceWarrior.useWeapon( );

The first part programs to an implementation because thealieninstance is typed as


the implementation,Alien.(AlienimplementsSpaceWarriorinterface.) In the second


part of the segment, thespaceWarriorinstance types as the supertype,SpaceWarrior.


However, it is instantiated using theEarthling( )constructor. As you can see, it


}

public function useWeapon( ):void
{
trace("Ka Boom!!!");
}
}
}


Example 8-4. Main.as


//Main.as
package
{
import flash.display.Sprite;
public class Main extends Sprite
{
public function Main( )
{
//Program to implementation
var alien:Alien=new Alien( );
alien.useWeapon( );


//Program to interface
var spaceWarrior:SpaceWarrior=new Earthling( );
spaceWarrior.useWeapon( );
}
}
}


Example 8-3. Earthling.as (continued)

Free download pdf