如何将单例传递给另一个对象,使该对象的所有实例都引用相同的单例

时间:2013-11-30 05:54:41

标签: javascript design-patterns singleton

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

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

我们也可以通过单例方法传递单例,以便NewObject可以访问单例方法吗?

2 个答案:

答案 0 :(得分:0)

将单例存储在变量中:

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

答案 1 :(得分:0)

即使我怀疑你在JavaScript中确实需要Singleton模式,我也是这样做的:

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();