为什么在辛格尔顿的AS3版本没有私人的构造? [英] Why there are no private constructors in AS3 version of Singleton?
问题描述
我很困惑:在AS3中,为什么我们保持Singleton类的构造函数公开
,而不是私人
,像在Java中?如果我们继续构造公开
,那么我们可以从外部直接访问它!
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的不支持私有构造函数。
为了强制执行Singleton模式,很多开发商会导致构造函数抛出一个异常,如果有已经创建一个单一实例。这将导致运行时错误,而不是编译时错误,但它确实prevent单身的不当使用。
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.
例如:
public static var instance:MySingleton;
public MySingleton(){
if (instance != null) {
throw new Error("MySingleton is a singleton. Use MySingleton.instance");
}else {
instance = this;
}
}
这篇关于为什么在辛格尔顿的AS3版本没有私人的构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!