AS3.0 Better Singletons

I've found a better more robust way of enforcing singletons in AS3.0

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( new SingletonEnforcer() );
  10.             return instance;
  11.         }
  12.  
  13.         public function Singleton( pvt:SingletonEnforcer )
  14.         {
  15.             // init class
  16.         }
  17.     }
  18. }
  19.  
  20. internal class SingletonEnforcer{}

Note: The class "SingletonEnforcer" is actually placed within the same .as file as the Singleton class, but placed outside the package{} parenthesis, therefore, the class "SingletonEnforcer" can only be accessed from within this .as file, so if the Singleton's constructor is called from anywhere else, you'll get an error.

7 Comments so far

  1. Unformatt / August 16th, 2007 11:28 pm

    This is nice - I guess ECMA doesn't like private constructors? Any reason not to include the PrivateClass in the package?

  2. gabriel / August 17th, 2007 7:55 am

    Exactly, ECMA doesn't allow private constructors. The PrivateClass is outside the package so that i can only be accessed by code within the current .as file (if it was in the package{} I'd assume it would be accessible elsewhere within the package.

  3. robert shearing / August 20th, 2007 1:23 am

    I discovered another implenentation by Daniel Hai on http://www.onflex.org/code/

    The private static instance variable is instantiated on declaration. Simple and clean:

    package
    {
    public class Singleton
    {

    private static var instance:Singleton = new Singleton();

    public function Singleton()
    {

    if( instance ) throw new Error( "Singleton and can only be accessed through Singleton.getInstance()" );
    }

    public static function getInstance():Singleton
    {
    return instance;
    }
    }
    }

  4. msn ifadeleri / September 24th, 2007 1:52 am

    Thanks YOu Alll

  5. you tube / September 24th, 2007 9:21 am

    Beatıfull one work, thank you

  6. indir / September 24th, 2007 12:39 pm

    I Thınk Such Knowledge see The Interest.. thanks.!

  7. Gabriel Handford / October 2nd, 2007 3:52 am

    Shouldn't it be:

    public static var get instance():Singleton { return getInstance(); }

    and change all the instance to _instance (to avoid the conflict)?

Leave a reply

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