08th Aug 2008

Enforcing a Singleton

Been doing some research on Cairngorm and in the process came across this little trick for enforcing singletons. ActionScript will not let you set the access modifier for a constructor to private and as such, despite having a singelton architecture, there would be nothing stopping someone from directly calling new Singleton, which defeat the purpose of a singleton in the first place. The solution involves using what amounts to a private class that is a required argument of the constructor. This looks like this:

package
{

/**
* …
* @author Jeremy Wischusen <cortex@visualflowdesigns.com>
*/
public class Singleton
{
private static var instance:Singleton;
public function Singleton(enforcer:SingletonEnforcer)
{

}
public static function getInstance():Singleton
{
if (Singleton.instance == null)
{
Singleton.instance = new Singleton(new SingletonEnforcer);
}
return Singleton.instance;

}
}

}
class SingletonEnforcer
{}

Notice the class definition for SingletonEnforcer is ourside of the package definition. When you define a class like this in the same file as a another class, it is only available to main class defined in the file (the one inside the package statement).  In other words the class is private. Since the constructor requires an instance of this class, trying to instantiate using new Singleton will throw an error since there is no way that an enforcer can be created and passed to the constructor other than within the Singleton class itself.

Hopefully in future versions of ActionScript we will have private constructors (along with method overloading just in case anyone is listening hint hint), but for now, this should do the trick.

Comments are closed.