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.

[as]
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();’ );
}
}
}
}
[/as]

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().

Comments are closed.