【问题标题】:How to pass a singleton to another Object such that all instance of that object refer to same singleton如何将单例传递给另一个对象,以使该对象的所有实例都引用同一个单例
【发布时间】:2013-11-30 05:54:40
【问题描述】:

请参考以下小提琴:http://jsfiddle.net/hBvSZ/5/

var NewObject = function () { 
//Singleton should be accessible here
    this.method1 = function() { }
};

我们也可以通过单例的方法只对 NewObject 访问的方式传递单例吗?

【问题讨论】:

  • 很可能你有一个XY Problem 而你根本不需要一个单例。
  • 问题不是实现单例,如果你可以检查我已经展示了单例的小提琴。问题是我们如何将它传递给一个对象,使得构造函数自动创建相同的单例实例。人们在问之前先谷歌..!!!

标签: javascript design-patterns singleton


【解决方案1】:

将单例存储在变量中:

var singleton;
function NewObject () {
    if (typeof singleton == 'undefined') {
        // initialize new object here.
    }
}

这是基本思想。

为避免全局命名空间污染,您可以使用闭包:

var NewObject = (function(){
    var singleton;
    return function () {
        if (typeof singleton == 'undefined') {
            // initialize new object here.
        }
    }
})();

【讨论】:

    【解决方案2】:

    尽管我怀疑你是否真的需要 JavaScript 中的单例模式,但我会这样做:

    var Client = (function() {
      var instance;
    
      var Client = function() {
    
      };
    
      Client.prototype.hello = function() {
        console.log("hello");
      };
    
      return {
        getInstance: function() {
          if (!instance) {
            instance = new Client();
          }
          return instance;
        },
        otherHelper: function() {
          console.log("look i'm helping!");
        },
      };
    })();
    
    var a = Client.getInstance();
    var b = Client.getInstance();
    
    a.hello(); // "hello"
    b.hello(); // "hello"
    
    console.log("a === b", a === b); // true
    
    Client.otherHelper(); // look i'm helping!
    

    如果你正在使用这个服务器端(例如 node.js),你可以这样做

    // client.js
    var instance;
    
    var getInstance = function getInstance() {
      if (!instance) {
        instance = new Client();
      }
      return instance;
    };
    
    var Client = function Client() {
    
    };
    
    Client.prototype.hello = function() {
      console.log("hello");
    };
    
    exports.getInstance = getInstance;
    

    那么用法就简单了

    // app.js
    var Client = require("./client");
    
    var myClient = Client.getInstance();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-23
      • 1970-01-01
      • 2011-06-07
      • 1970-01-01
      相关资源
      最近更新 更多