Futurescale, Inc. PureMVC Home

The PureMVC Framework Code at the Speed of Thought


Over 10 years of community discussion and knowledge are maintained here as a read-only archive.

New discussions should be taken up in issues on the appropriate projects at https://github.com/PureMVC

Pages: [1]
Print
Author Topic: Interesting AS3 Singleton Code  (Read 6895 times)
trilec
Sr. Member
****
Posts: 52



View Profile WWW Email
« on: April 17, 2008, 04:21:03 »

:
package
{
    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 ...

T
Logged
puremvc
Global Moderator
Hero Member
*****
Posts: 2871



View Profile WWW Email
« Reply #1 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.

-=Cliff>


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.

-=Cliff>
Logged
Pages: [1]
Print