Friday, September 9, 2011

Singleton Class in ActionScript

As in JAVA, ActionScript does not have a private constructor. So, the job of creating a singleton class is not really simple. However, we can create Singleton classes in ActionScript. Below is a simple class that does the trick.

package utils
{
public class SingletomExample
{
private static var instance:SingletomExample;
public function SingletomExample(enforcer:SingletonEnforcer)
{
if (!enforcer)
{
throw new Error("Cannot instantiate a Singleton class. Use getInstance() instead");
}
}
public static function getInstance():SingletomExample
{
if (!instance)
{
instance = new SingletomExample(new SingletonEnforcer());
}
return instance;
}
}
}

class SingletonEnforcer{}

And lo and behold, your Singleton class is here.

Some Explanation:
The code is pretty much self explanatory. A class "SingletonEnforcer" is added to the package. This is an internal class that no one can access outside the class. Using internal class this to enforce the Singleton makes it impossible to break the Singleton nature.

Hope this helps..

No comments :