我见过很多单身人士的实现,我只想要一个单身人士
1.-第一次调用的实例2.-实例只有一次(duh)
因此,在性能和最低内存消耗方面,最好的实现是什么?
例1
package Singletons
{
public class someClass
{
private static var _instance:someClass;
public function AlertIcons(e:Blocker):void{}
public static function get instance():someClass{
test!=null || (test=new someClass(new Blocker()));
return _instance;
}
}
}
class Blocker{}
Run Code Online (Sandbox Code Playgroud)
例题
public final class Singleton
{
private static var _instance:Singleton = new Singleton();
public function Singleton()
{
if (_instance != null)
{
throw new Error("Singleton can only be accessed through Singleton.instance");
}
}
public static function get instance():Singleton
{
return _instance;
}
}
Run Code Online (Sandbox Code Playgroud)
例3
package {
public class SingletonDemo {
private static var instance:SingletonDemo;
private static var allowInstantiation:Boolean;
public static function getInstance():SingletonDemo {
if (instance == null) {
allowInstantiation = true;
instance = new SingletonDemo();
allowInstantiation = false;
}
return instance;
}
public function SingletonDemo():void {
if (!allowInstantiation) {
throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jas*_*ves 13
示例2,但有一个扭曲,因为你应该允许新的Singleton()被调用至少一次,我不喜欢实例化的东西,直到我需要它们,因此第一次调用instance()实际上创建实例...后续调用抓住原来的.
编辑:如果你打电话,播种它也可以允许
var singleton:Singleton = new Singleton();
Run Code Online (Sandbox Code Playgroud)
它将工作...但所有未来的尝试将抛出错误并强制使用getInstance()方法
public final class Singleton{
private static var _instance:Singleton;
public function Singleton(){
if(_instance){
throw new Error("Singleton... use getInstance()");
}
_instance = this;
}
public static function getInstance():Singleton{
if(!_instance){
new Singleton();
}
return _instance;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10175 次 |
| 最近记录: |