Singleton in AS3
Singleton classes are one of the simple but very effective design patterns. Creating singleton classes in Java, C++ or even AS2 for that matter is very straightforward.
But in AS3, which is based on ECMAScript private constructors are not supported. The following is how you enforce a user of your library to have a singleton object in AS3.
Even the SingletonEnforcer class should go into the Example.as
package com.ciddu.sharath
{
public class Example
{
private static var _instance:Example;
public function Example(obj:Singleton)
{
if(obj == null)
{
throw Error(“This is a singleton class. Use getInstance instead”);
}
}
public function getInstance():Example
{
if(Example._instance == null)
{
var obj:SingletonEnforcer = new SingletonEnforcer();
Example._instance = new Example(obj);
}
return Example. _instance;
}
}
}
class SingletonEnforcer
{
}
Since the class SingletonEnforcer is present outside the package, it is not accessible outside Example.as
But at the same time if someone tries to create an object using new Example(), it will throw argument mismatch error during compilation.
If still someone tries to use new Example(null), a runtime exception is thrown.




