强制共享外部模块中的单例模式

时间:2018-04-06 22:15:26

标签: javascript node.js webpack singleton

假设我们有2个js模块(A,B)需要一个公共模块'C',它是一个Singleton或者有静态方法。 如果它们都需要相同的C实例,那么一切都很好。但是如果由于某种原因,require方法将解析为不同的文件(例如,如果它们需要不同的版本或者如果C模块被捆绑在其中一个中)那么我们将有2个不同的C实例,即使它被设置为单身人士

即使代码可以存在两次,我们如何在javascript中强制执行单例模式? 我可以使用全局namesapce,还是有更好的模式? 如果是这样,我如何正确使用全球?

1 个答案:

答案 0 :(得分:0)

似乎使用全局范围是唯一的方法,但有一些方法可以使用符号使这更安全。

// create a unique, global symbol name
// -----------------------------------

const FOO_KEY = Symbol.for("My.App.Namespace.foo");

// check if the global object has this symbol
// add it if it does not have the symbol, yet
// ------------------------------------------

var globalSymbols = Object.getOwnPropertySymbols(global);
var hasFoo = (globalSymbols.indexOf(FOO_KEY) > -1);

if (!hasFoo){
  global[FOO_KEY] = {
    foo: "bar"
  };
}

// define the singleton API
// ------------------------

var singleton = {};

Object.defineProperty(singleton, "instance", {
  get: function(){
    return global[FOO_KEY];
  }
});

// ensure the API is never changed
// -------------------------------

Object.freeze(singleton);

// export the singleton API only
// -----------------------------

module.exports = singleton;

基于教程found here