Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 623
TrexTroy Avatar asked Nov 29 '22 14:11

TrexTroy


1 Answers

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;
    }
}
like image 121
Sam DeHaan Avatar answered May 16 '23 06:05

Sam DeHaan