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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With