[英]Is a Node.js module a singleton?
我曾經以這種方式實現單例:
class MySomething {
constructor(props) {}
}
let myInstance = null;
module.exports = (props) => {
//first time call
if(props) {
myInstance = new MySomething (props);
return myInstance;
} else {
return myInstance;
}
這假設在 app.js (入口文件)我將首先調用:
require('./MySomething')(props)
然后在我使用的項目中的任何地方:
const instanceOfSomething = require('./MySomething')();
我發現每次我得到一個新實例時!
我的代碼有什么問題?
我也試過這樣:
class MySomething {...}
const mySomething = (function() {
let myInstance = null;
return {
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
})();
module.exports = mySomething;
從不同文件導入這個模塊時我遇到了一些問題,任何人都可以向我解釋一下嗎?
文件的每個要求都會創建 mySomething 的新實例
更新
我現在嘗試了這個例子:
class MySomething {...}
const mySomething = {
myInstance: null,
init: function() {
myInstance = new MySomething();
},
getInstance: function() {
return myInstance ;
}
}
};
module.exports = mySomething;
也出現了同樣的問題,可能和我的項目結構有關,這里解釋一下:
下面的代碼屬於模塊“事實”
fact 文件夾包含一個名為“dao”的文件夾,此文件夾包含我擁有的 fact/index.js 中的 MySomething.js(單例):
const Localstorage = require('./dao/MySomething');
exports.init = (path) => {
Localstorage.init(path)
}
exports.Localstorage = Localstorage;
現在在一個名為“core”的文件夾中,其中包含“facts”文件夾,我再次在“index.js”中重新導出了 Localstorage,如下所示:
const facstModule = require('./facts');
exports.Localstorage = facstModule.Localstorage;
然后在包含“Runtime.js”的“schedule”文件夾中我寫:
const { Localstorage } = require('../core');
setTimeout(() => {
const localstorageIns = Localstorage.getInstance(); //this is always null!
}, 5000)
在 app.js 文件(入口點)中,我做了:
const facts = require('./src/facts');
facts.init(__dirname);
通常會在超時執行回調之前創建實例,但我注意到有兩個 Localstorage 實例是單例的
文件的每個要求都會創建 mySomething 的新實例,因為每次您使用init
方法和getInstance
方法返回新對象時。
如果你需要單例,你需要這樣做:
class MySomething {
constructor() {
if (!MySomething.instance) {
MySomething.instance = this;
}
}
getInstance: function() {
return MySomething.instance;
}
}
module.exports = MySomething;
做單例最干凈的方法是
class MyClass () { ... }
module.exports = new MyClass()
如果您需要一個實例化一次的單例,我會這樣做:
class MyClass () { ... }
let myClass
const MyClassSingleton = (...args) => {
if (myClass) {
return myClass
}
myClass = new MyClass(...args)
return myClass
}
module.exports = MyClassSingleton
class Singleton {
constructor() {
this.my_obj;
}
static makeObject() {
if (!this.my_obj) {
this.my_obj = new Singleton();
}
return this.my_obj;
}
add() {
return 1
}
}
// so to get the object we need to call the makeobject method
const obj = Singleton.makeObject()
console.log(obj.add());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.