Search code examples
actionscript-3apache-flexactionscriptflex3

Why there are no private constructors in AS3 version of Singleton?


I am confused: In AS3, why do we keep the Singleton class constructor public and not private, like in Java? If we keep the constructor public, then we can directly access it from the outside!

Please check the MODEL part in this example.


Solution

  • Actionscript 3 does not support private constructors.

    In order to enforce the singleton pattern, many developers cause the constructor to raise an exception if there is already a singleton instance created. This will cause a runtime error, instead of a compile time error, but it does prevent the singleton's inappropriate use.


    Example:

    public static var instance:MySingleton;
    
    public MySingleton(){
        if (instance != null) {
            throw new Error("MySingleton is a singleton. Use MySingleton.instance");
        }else {
            instance = this;
        }
    }