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:
-
package
-
{
-
public class Singleton
-
{
-
public static var instance:Singleton;
-
-
public static function getInstance():Singleton
-
{
-
if( instance == null ) instance = new Singleton( getInstance );
-
return instance;
-
}
-
-
public function Singleton( caller:Function )
-
{
-
if( caller == Singleton.getInstance )
-
{
-
// instantiate class here
-
}
-
else
-
{
-
throw new Error( 'Singleton is a singleton, use getInstance();' );
-
}
-
}
-
}
-
}
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
Leave a reply
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.
and you do that stuff for fun?