ActionScript 3 Singleton Pattern Singleton enforcer via private instance


Example

In this approach, the single is accessed via the static method:

Singleton.getInstance();

To enforce only one instance of the singleton, a private static variable retains the instance, while any additional attempts to instantiate an instance are enforced within the constructor.

package {

public class Singleton {

    /** Singleton instance */
    private static var _instance: Singleton = new Singleton();

    /** Return singleton instance. */
    public static function getInstance():Singleton {
        return _instance;
    }

    /** Constructor as singleton enforcer. */
    public function Singleton() {
        if (_instance)
            throw new Error("Singleton is a singleton and can only be accessed through Singleton.getInstance()");
    }

}
}