PureMVC Architects Lounge

Announcements and General Discussion => Architecture => Topic started by: trilec on April 17, 2008, 04:21:03

Title: Interesting AS3 Singleton Code
Post by: trilec on April 17, 2008, 04:21:03
    public class Singleton
        public static var instance:Singleton;
        public static function getInstance():Singleton
            if( instance == null ) instance = new Singleton( new SingletonEnforcer() );
            return instance;
        public function Singleton( pvt:SingletonEnforcer )
            // init class
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.

reference: http://blog.pixelbreaker.com/category/flash/actionscript-30/

Also some interesting stuff on Performance Tuning by Gary Grossman

...it became clear that class constructors are interpreted, not JIT compiled, so all I had to do was move the code out of the constructor, into an init() function, and call if after the constructor, this shaved a huge amount of time off the initial build ...


Title: Re: Interesting AS3 Singleton Code
Post by: puremvc on April 18, 2008, 07:57:32
Yep. This is actually a very nice way of doing the Singleton in AS3. IMHO, its the most elegant way, by far.

I considered this style for PureMVC's Singletons back at the beginning but decided that it was tied too deeply to a 'special feature' of ActionScript. This 'scope of the file' business seemed a little un-oopy. As ECMA/ActionScript evolves, I could see this functionality being lopped off as a 'useless appendage' or more likely being modified to operate like an Static Nested Classes or Inner Classes in Java. Either way I didn't want PureMVC to be affected.

So I stuck with the more ordinary way of doing it in hopes it would port well, and be less likely to become deprecated or in the future.


In reality, it turns out every language has some preferred way to do the Singleton so the exact implementation doesn't really matter much when it comes to porting.