AS3.0 Singletons

While I've been getting up to speed with my AS3 over the past few months, there have been a few things which are really useful to know and took a bit of digging about to find.

As class constructors in ActionScript 3.0 must be public, there's not a really clean way to force a class to be a singleton as there is in ActionScript 2.0 or Java say.

Actionscript:
  1. package
  2. {
  3.     public class Singleton
  4.     {
  5.         public static var instance:Singleton;
  6.        
  7.         public static function getInstance():Singleton
  8.         {
  9.             if( instance == null ) instance = new Singleton( getInstance );
  10.             return instance;       
  11.         }
  12.        
  13.         public function Singleton( caller:Function )
  14.         {
  15.             if( caller == Singleton.getInstance )
  16.             {
  17.                 // instantiate class here   
  18.             }
  19.             else
  20.             {
  21.                 throw new Error( 'Singleton is a singleton, use getInstance();' );
  22.             }
  23.         }
  24.     }
  25. }

It's pretty simple, you can't call new Singleton() because the compiler will be expecting an argument, and if you do pass an argument, it will throw an Error because the caller is not the Singleton.getInstance method.

So you can only access this class by calling Singleton.getInstance().

2 Comments so far

  1. Si / July 13th, 2007 10:55 am

    That's very clever using an argument to make it compiler-friendly. It's a bit sickening that AS3 still needs these kind of hacks though.

    Having said that, the hack for creating Singletons in Objective-C is pretty unbelievable.

  2. pixelbreaker / July 13th, 2007 12:18 pm

    and you do that stuff for fun?

Leave a reply

*
To prove that you're not a bot, enter this code
Anti-Spam Image