I completed my homework and got a great result. But I just want to check if this is the best way to create singleton instances or is them any other way:
I created a singleton object using a module (closure) template, for example, "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());
Actual single object (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;
Then Singleton object user 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;
Singleton Object User 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;
Please note that Single User 1 and User 2 are for a specific purpose according to my project, it is just a prototype of a real-world problem.
My question is: I'm sure this creates one instance of the class (as I checked using app.js above). But is this the best way?