ActionScript 3.0 Design Patterns

(Chris Devlin) #1
When to Use the Singleton Pattern | 119

The first thing to note about this Singleton script is that it imports packages and


classes. Up to this point, all of the imports were done in the scripts that called the


Singleton class. However, whenever a method or property has a reference, including


abstract ones, to a class in a package, it needs to import that class. Likewise, you’ll


see that the class (DoMusic) that implements the Singleton class (Tuner) requires no


further import of the objects associated with the packages and classes already


imported in the Singleton class.


Because this application simply makes sure that only one MP3 file is played at any


time, the Singleton implementation is very simple. Example 3-13 shows the code for


this class:


Save Example 3-13 asDoMusic.asin the same folder asTuner.as. Open a Flash docu-


ment file, typeDoMusicin the Class document window in the Properties panel, and


save it asMusic.flain the folder with the two ActionScript files. Finally, place any


}

//Stop Play
public function stopMe ( ):void
{
if (_goChannel != null)
{
_goChannel.stop ( );
}
}
}
}


class PrivateClass
{
public function PrivateClass ( )
{
trace ("PrivateClass called");
}
}


Example 3-13. DoMusic.as


package
{
import flash.display.Sprite;
public class DoMusic extends Sprite {
public function DoMusic( ) {
var playOne:Tuner = Tuner.getInstance( );
//Use any MP3 file you have available
playOne.playMe("blues.mp3");
}
}
}


Example 3-12. Tuner.as

Free download pdf