ActionScript 3.0 Design Patterns

(Chris Devlin) #1

118 | Chapter 3: Singleton Pattern


for playing the selected tune. If it finds a non-nullvalue, it means it better stop any


current sounds associated with theSoundChannelinstance before loading up and


playing a new MP3 file. In that way, you ensure that you won’t have multiple tunes


playing simultaneously. The moral to this particular application is this:


Just because you use a Singleton design pattern does not mean that your application
will work with the single outcome you want. You must design your Singleton to
ensure that the single outcome you want takes place in the way you want.

With the moral in mind, you can now create your Singleton for making sure that


only one MP3 file is allowed to play at once. Enter the script shown in Example 3-12


in an ActionScript file, and save it asTuner.as.


Example 3-12. Tuner.as


package
{
import flash.net.URLRequest;
import flash.media.Sound;
import flash.media.SoundChannel;
public class Tuner
{
private var _goChannel:SoundChannel;
private var _tuneUp:Sound;
private var _tuneIn:URLRequest;
//Singleton instance
private static var _instance:Tuner;


//Singleton constructor
public function Tuner (pvt:PrivateClass)
{
}
//Singleton constructor method
public static function getInstance ( ):Tuner
{
if (Tuner._instance == null)
{
Tuner._instance=new Tuner(new PrivateClass );
trace ("Tuner instantiated");
}
return Tuner._instance;
}
//Start Play
public function playMe (song:String):void
{
if (_goChannel != null)
{
_goChannel.stop ( );
}
_tuneUp=new Sound ;
_tuneIn=new URLRequest(song);
_tuneUp.load (_tuneIn);
_goChannel=_tuneUp.play( );

Free download pdf