【游客模式】——注册会员,加入11RIA 闪客社区吧!一起见证Flash的再次辉煌……
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
本帖最后由 cdt 于 2017-11-24 15:19 编辑
方法一:(显式允许new一次) package { import flash.errors.IllegalOperationError; import flash.events.EventDispatcher; import flash.utils.Dictionary; import flash.utils.getQualifiedClassName;
public class DT1 extends EventDispatcher { private static var dict:Dictionary = new Dictionary();
public function DT1() { trace("运行DT1 "); var ref:Class = this["constructor"] as Class; if (dict[ref]) { throw new IllegalOperationError((getQualifiedClassName(this) + " 只允许实例化一次!")); } else { dict[ref] = this; } } /** * 获取单例类,若不存在则创建 * * @param ref继承自DT1的类 * @return * */
public static function getInstanceOrCreate(ref:Class):* { if (dict[ref] == null) { dict[ref] = new ref(); }
return dict[ref]; }
}
} 方法二:(显式允许new一次) package { import flash.errors.IllegalOperationError; import flash.utils.getQualifiedClassName; public class DT2 { private static var _instance:DT2 = null; public function DT2() { trace("运行DT2 "); if(_instance) throw new IllegalOperationError(getQualifiedClassName(this)+" 只运行实例化一次!"); } public static function getInstance():DT2 { return _instance ||= new DT2(); }
}
} 方法三:(隐式允许new一次 利用包外类看上去好像一次new都不行) package { import flash.errors.IllegalOperationError; import flash.utils.getQualifiedClassName; public class DT3 { private static var _instance:DT3 = null; public function DT3(instance:SureSingle=null) { if(instance==null) throw new IllegalOperationError(getQualifiedClassName(this)+" 是单例!"); } public static function getInstance():DT3 { return _instance ||= new DT3(new SureSingle()); } } } internal class SureSingle{} |