AS3 单例实现 [英] AS3 singleton implementations
问题描述
我见过很多单例的实现,我只想要一个单例
I have seen so many implementations of singletons around, and i just want a singleton that
1.- 第一次调用的实例2.- 实例只有一次(废话)
1.- instances on the first call 2.- instances only once (duh)
那么在性能和最低内存消耗方面,最好的实现是什么?
So in performance and lowest memory consumtion, whats the best implementation for this?
示例 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{}
示例 2
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;
}
}
示例 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.");
}
}
}
}
推荐答案
示例 2 但有一个转折,因为您应该允许至少调用一次 new Singleton() 并且我不喜欢在需要之前实例化事物,因此,对 instance() 的第一次调用实际上创建了实例……随后的调用会获取原始实例.
example 2 but with a twist since you should allow new Singleton() to be called at least once and I don't like instantiating things until I need them, thus the first call to instance() actually creates the instance... subsequent calls grab the original.
播种它如何允许如果你打电话
Sowed how it can also allow for if you call
var singleton:Singleton = new Singleton();
它会工作...但所有未来的尝试都会抛出错误并强制使用 getInstance() 方法
it will work... but all future tries will throw the error and force use of the getInstance() method
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;
}
}
这篇关于AS3 单例实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!