我完成了我的家庭作业并取得了完美的成绩.但我只是想检查一下,这是创建单例实例的最佳方式还是其他任何方式:
我使用模块模式(闭包)创建了一个单例对象,"app.js"
var singleton1 = require('./singletonUser1'); console.dir(singleton1.getlocalvariable()); singleton1.setlocalvariable(20); console.dir(singleton1.getlocalvariable()); var singleton2 = require('./singletonUser2'); console.dir(singleton2.getlocalvariable()); singleton2.setlocalvariable(30); console.dir(singleton.getlocalvariable());
实际单例对象(singleton.js):
var singleton = (function () { var localvariable = 10; return { getlocalvariable: function () { console.dir('This is getInstance'); return localvariable; }, setlocalvariable: function (value) { console.dir('This is setlocalvariable'); localvariable = value; }, }; })(); module.exports = singleton;
然后Singleton对象用户1(singletonUser1.js):
var singletonUser1 = (function () { var singleton = require('./singleton'); return { getlocalvariable: function () { console.dir('This is singletonUser1---getlocalvariable'); return singleton.getlocalvariable(); }, setlocalvariable: function (value) { console.dir('This is singletonUser1---setlocalvariable'); singleton.setlocalvariable(value); }, }; })(); module.exports = singletonUser1;
单例对象用户2(singletonUser2.js)
var singletonUser2 = (function () { var singleton = require('./singleton'); return { getlocalvariable: function () { console.dir('This is singletonUser2222---getlocalvariable'); return singleton.getlocalvariable(); }, setlocalvariable: function (value) { console.dir('This is singletonUser22222---setlocalvariable'); singleton.setlocalvariable(value); }, }; })(); module.exports = singletonUser2;
请注意,单用户1和用户2,是出于某个目的,根据我的项目,上面只是现实世界问题的原型.
我的问题是,我确信这是创建一个类的单个实例(我使用上面的app.js检查).但这是最好的方法吗?
var Singleton = (function(){
function Singleton(){
this.localVariable = 5;
}
// Object can have instance methods as usually.
Singleton.prototype.getLocalVariable = function() {
return this.localVariable;
};
var instance;
return function() {
if (!instance) {
instance = new Singleton();
}
return instance;
};
})();
var instance1 = new Singleton();
var instance2 = new Singleton();
console.log(instance1 === instance2); // true
console.log(instance1.localVariable, instance2.localVariable); // 5 5
instance1.localVariable = 20;
console.log(instance1.localVariable, instance2.localVariable); // 20 20
console.log(instance1.getLocalVariable()); // 20