Yes. When the caching of Node's modules fails, the singleton design pattern also fails. I made adjustments to the code example to ensure it runs correctly on OSX:
var sg = require("./singleton.js");
var sg2 = require("./singleton.js");
sg.add(1, "test");
sg2.add(2, "test2");
console.log(sg.getSocketList(), sg2.getSocketList());
This results in the expected output as intended by the author:
{ '1': 'test', '2': 'test2' } { '1': 'test', '2': 'test2' }
However, a minor modification can disrupt the caching. On OSX, try the following:
var sg = require("./singleton.js");
var sg2 = require("./SINGLETON.js");
sg.add(1, "test");
sg2.add(2, "test2");
console.log(sg.getSocketList(), sg2.getSocketList());
Alternatively, on Linux:
% ln singleton.js singleton2.js
Then update the sg2
require line to:
var sg2 = require("./singleton2.js");
With this change, the singleton behavior is disrupted:
{ '1': 'test' } { '2': 'test2' }
Finding a solution to this challenge is tricky. If you are willing to compromise and risk potential issues that come with polluting the global namespace, you could modify the author's getInstance()
and exports
lines like so:
singleton.getInstance = function(){
if(global.singleton_instance === undefined)
global.singleton_instance = new singleton();
return global.singleton_instance;
}
module.exports = singleton.getInstance();
In my experience, I've never encountered a scenario in a production environment where such modifications were necessary. Personally, I have not found the use of the singleton pattern essential in Javascript.