代码之家  ›  专栏  ›  技术社区  ›  Kaze no Koe

javascript:最佳单例模式[duplicate]

  •  92
  • Kaze no Koe  · 技术社区  · 15 年前

    可能重复:
    Simplest/Cleanest way to implement singleton in JavaScript?

    我将这个模式用于单重态,在这个例子中,单重态是planetearth:

    var NAMESPACE = function () {
    
        var privateFunction1 = function () {
            privateFunction2();
        };
    
        var privateFunction2 = function () {
            alert('I\'m private!');
        };
    
        var Constructors = {};
    
        Constructors.PlanetEarth = function () {
            privateFunction1();
            privateFunction2();
        };
    
        Constructors.PlanetEarth.prototype = {
            someMethod: function () {
                if (console && console.log) {
                    console.log('some method');             
                }
            }
        };
    
        Constructors.Person = function (name, address) {
            this.name = name;
            this.address = address;
        };
    
        Constructors.Person.prototype = {
            walk: function () {
                alert('STOMP!');
            }
        };
    
        return {
            Person: Constructors.Person, // there can be many
            PlanetEarth: new Constructors.PlanetEarth() // there can only be one!
        };
    
    }();
    

    自从 行星地球 构造函数仍然是私有的,只能有一个。

    现在,有人告诉我,这种自我烹饪的东西并不是最好的,主要是因为我没有受过学术教育,我倾向于用愚蠢的方式解决问题。作为一个 更好的 替代我的方法,其中 更好的 定义为 风格更好和/或更强大 ?

    4 回复  |  直到 6 年前
        1
  •  154
  •   tomasdev    6 年前

    (1)更新2019:ES7版本

    class Singleton {
        static instance;
    
        constructor() {
            if (instance) {
                return instance;
            }
    
            this.instance = this;
        }
    
        foo() {
            // ...
        }
    }
    
    console.log(new Singleton() === new Singleton());
    

    (2)ES6版本

    class Singleton {
        constructor() {
            const instance = this.constructor.instance;
            if (instance) {
                return instance;
            }
    
            this.constructor.instance = this;
        }
    
        foo() {
            // ...
        }
    }
    
    console.log(new Singleton() === new Singleton());
    

    找到的最佳解决方案: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

    function MySingletonClass () {
    
      if (arguments.callee._singletonInstance) {
        return arguments.callee._singletonInstance;
      }
    
      arguments.callee._singletonInstance = this;
    
      this.Foo = function () {
        // ...
      };
    }
    
    var a = new MySingletonClass();
    var b = MySingletonClass();
    console.log( a === b ); // prints: true
    

    对于那些想要严格版本的人:

    (function (global) {
      "use strict";
      var MySingletonClass = function () {
    
        if (MySingletonClass.prototype._singletonInstance) {
          return MySingletonClass.prototype._singletonInstance;
        }
    
        MySingletonClass.prototype._singletonInstance = this;
    
        this.Foo = function() {
          // ...
        };
      };
    
    var a = new MySingletonClass();
    var b = MySingletonClass();
    global.result = a === b;
    
    } (window));
    
    console.log(result);
    
        2
  •  24
  •   bobince    15 年前

    为什么要为单个对象使用构造函数和原型?

    以上相当于:

    var earth= {
        someMethod: function () {
            if (console && console.log)
                console.log('some method');                             
        }
    };
    privateFunction1();
    privateFunction2();
    
    return {
        Person: Constructors.Person,
        PlanetEarth: earth
    };
    
        3
  •  18
  •   Community CDub    8 年前

    Extending 上面的文章由tom撰写,如果您需要一个类类型声明并使用变量访问singleton实例,下面的代码可能会有帮助。我喜欢这个符号,因为代码有点自我指导。

    function SingletonClass(){
        if ( arguments.callee.instance )
            return arguments.callee.instance;
        arguments.callee.instance = this;
    }
    
    
    SingletonClass.getInstance = function() {
        var singletonClass = new SingletonClass();
        return singletonClass;
    };
    

    要访问singleton,您需要

    var singleTon = SingletonClass.getInstance();
    
        4
  •  1
  •   Alain Lecluse    13 年前
    function SingletonClass() 
    {
        // demo variable
        var names = [];
    
        // instance of the singleton
        this.singletonInstance = null;
    
        // Get the instance of the SingletonClass
        // If there is no instance in this.singletonInstance, instanciate one
        var getInstance = function() {
            if (!this.singletonInstance) {
                // create a instance
                this.singletonInstance = createInstance();
            }
    
            // return the instance of the singletonClass
            return this.singletonInstance;
        }
    
        // function for the creation of the SingletonClass class
        var createInstance = function() {
    
            // public methodes
            return {
                add : function(name) {
                    names.push(name);
                },
                names : function() {
                    return names;
                }
            }
        }
    
        // wen constructed the getInstance is automaticly called and return the SingletonClass instance 
        return getInstance();
    }
    
    var obj1 = new SingletonClass();
    obj1.add("Jim");
    console.log(obj1.names());
    // prints: ["Jim"]
    
    var obj2 = new SingletonClass();
    obj2.add("Ralph");
    console.log(obj1.names());
    // Ralph is added to the singleton instance and there for also acceseble by obj1
    // prints: ["Jim", "Ralph"]
    console.log(obj2.names());
    // prints: ["Jim", "Ralph"]
    
    obj1.add("Bart");
    console.log(obj2.names());
    // prints: ["Jim", "Ralph", "Bart"]