ActionScript 3.0 Design Patterns

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

In order to provide a broad but by no means exhaustive view of how the Singleton


can be employed, we will step through three examples. First, the Alert example is a


simple one that shows how a single message can be placed on the stage. It is meant


to represent those kinds of interfaces where the user gets a message, such as in a dia-


log bo xor similar feedback mechanism. Only a single instance of the feedback


should be instantiated, to avoid contradictory messages. However, the example also


shows how to connect the class to display objects on the stage. As such, it is instruc-


tive for working with display programming in ActionScript 3.0.


The second example is used for playing an MP3 file. In most situations where you


play media, whether it’s a MP3 file or a video, you want to hear or see only one


media element at a time. Playing Bach and a song by Gnarls Barkley simultaneously


may create a racket that neither Johann Sebastian nor Gnarls would want to hear. A


Singleton class helps to keep the play sequential, with no more than one playing at


the same time.


The third example uses a simple shopping cart to illustrate how a single instance can


be used to keep track of a running total. In situations where your application needs


an absolutely no-questions-about-it single instance for keeping track of financial


accumulations, a Singleton can be crucial. The example also shows how to link a


class to a stage-created movie clip and embedded text field.


A Single Alert Message


Because clear communication is the cru xof good site design, mi xed messages need


to be kept out of all web applications. By using a Singleton pattern, you can help


assure that you have a single source for messages to the user. This way, you’re less


likely to send two contradictory messages. The following application uses a Single-


ton for that purpose. It’s designed so that no matter where a message originates, it


has only this one instance to deliver it.


To get started, open a new ActionScript file, and type in the script shown in


Example 3-10.


Example 3-10. Alert.as


package
{
public class Alert
{
private var _msg:String;
private static var _instance:Alert;
public function Alert(pvt:PrivateClass) {


}
public static function getInstance( ):Alert
{
if(Alert._instance == null)

Free download pdf