ActionScript 3.0 Design Patterns

(Chris Devlin) #1

120 | Chapter 3: Singleton Pattern


MP3 file in the same folder, and rename itblues.mp3. (You may keep the MP3 file’s


original name and change the reference name in the script fromblues.mp3to the


name of your MP3 file—just make sure that the reference name and the filename are


the same.) When you test your movie, you should hear your MP3 file play.


In a more realistic example, the application is likely to have several sound selections


from which to choose, and the Singleton ensures that only one plays at one time.


Because the method for playing an MP3 file is abstracted in the Singleton class, if


another tune is called through the Singleton, it employs the single instance of the


class to start the new tune. This particular Singleton takes care of the sound “house-


keeping” by making sure that any currently playingSoundChannel instances are


stopped, and so it does more than just ensure that only a single instance of the class


is instantiated. Example 3-14 provides the necessary code. Save the file as


DoMusicBtn.as in the same folder as theTuner.as file.


EExample 3-14. DoMusicBtn.as


package
{
import flash.events.MouseEvent;
import flash.display.Sprite;


public class DoMusicBtn extends Sprite
{
private var _playOne:SongPlay=new SongPlay( );
private var _playTwo:SongPlay=new SongPlay( );
private var _stopSong:SongPlay=new SongPlay( );
private var playTune:Tuner;


public function DoMusicBtn ( )
{
playTune = Tuner.getInstance( );
//Set up buttons
addChild (_playOne);
_playOne.x=30;
_playOne.y=50;
addChild (_playTwo);
_playTwo.x=30;
_playTwo.y=150;
addChild (_stopSong);
_stopSong.x=130;
_stopSong.y=100;


//Set up event listeners
_playOne.addEventListener (MouseEvent.CLICK,doOne);
_playTwo.addEventListener (MouseEvent.CLICK,doTwo);
_stopSong.addEventListener (MouseEvent.CLICK,doStop);
}
//Methods
function doOne (e:MouseEvent):void
{

Free download pdf