AS3单例实现

时间:2012-11-10 01:19:18

标签: actionscript-3

我见过很多单身人士的实现,我只想要一个单身人士

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{}

例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.");
            }
        }
    }
}

1 个答案:

答案 0 :(得分:13)

示例2,但有一点麻烦,因为你应该允许新的Singleton()被调用至少一次,我不喜欢实例化的东西,直到我需要它们,因此第一次调用instance()实际上创建了实例..后续的电话抓住了原来的电话。

编辑:如果你打电话

播种它也是如何允许的
var singleton:Singleton = new Singleton();

它会起作用......但是所有未来的尝试都会抛出错误并强制使用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;
    }
}