实现AS3的Singleton的两种方法
- 作者:柳大·Poechant
- 邮箱:zhongchao.ustc#gmail.com (# -> @)
- 博客:blog.csdn.net/poechant
- 日期:April 8th, 2012
1 构造函数随机参数
利用随机数,当做构造函数的参数,实现构造函数无法随意调用。
package {
class Singleton {
private static var _instance:Singleton = null;
// secret known only to this class
private static const secret:Number = Math.random();
/**
* @private
*/
public function Singleton(enforcer:Number) {
if (enforcer != secret) {
throw new Error("Error: use Singleton.instance instead");
}
}
/**
* Global single instance
*/
public static function get instance():Singleton {
if (_instance == null) {
_instance = new Singleton(secret);
}
return _instance;
}
}
}
2 私有类
在 AS3 文件内部的包定义外部实现一个类,这个类就是文件内私有的。
package
{
class Singleton {
private static var _instance:Singleton = null;
public function Singleton(enforcer:PrivateClass) {
}
public function getInstance():Singleton {
if (_instance == null) {
_instance = new Singleton();
}
return _instance;
}
}
}
class PrivateClass {
public PrivateClass() {
}
}
-
转载请注明来自柳大的CSDN博客:blog.csdn.net/poechant
-