为什么在 AS3 版本的 Singleton 中没有私有构造函数? [英] Why there are no private constructors in AS3 version of Singleton?
问题描述
我很困惑:在 AS3 中,为什么我们保留单例类构造函数 public
而不是 private
,就像在 Java 中一样?如果我们保持构造函数public
,那么我们就可以直接从外部访问它!
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!
请检查本示例中的模型部分.
推荐答案
Actionscript 3 不支持私有构造函数.
为了强制执行单例模式,如果已经创建了单例实例,许多开发人员会导致构造函数引发异常.这将导致运行时错误,而不是编译时错误,但它确实防止了单例的不当使用.
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 版本的 Singleton 中没有私有构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!