Singleton in AS3

4 Jul

Lots of discussion, loads of different versions, I’m using this and still haven’t noted any “flaws”:

// ActionScript file
package
{
   public class MyTestClass
   {
   /* singleton */ { trace ( "Initialising MyTestClass singleton" ); _singleton = true; _instance = new MyTestClass ( ); _singleton = false;  }
     private static var _instance : MyTestClass;
     private static var _singleton : Boolean;

     public var strTestVariable : String = "Was the singleton test successful?";

     public function MyTestClass ( ) : void
     {
     trace ( "Constructor" );

     if ( ! _singleton )
     {
       throw new Error ( "Error: Instantiation failed\n       Please use MyTestClass.getInstance ( )" );
     }
   }

   public static function getInstance ( ) : MyTestClass
   {
     return _instance;
   }
  }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: