5

我已经看到了很多单例的实现,我只想要一个单例

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

1 回答 1

13

示例 2 但有一个转折,因为您应该允许至少调用一次 new 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;
    }
}
于 2012-11-10T03:15:34.777 回答