Reputation: 10703
I am working on a home automation project in NodeJS with several modules. These modules need access to data devices within a central DeviceManager
. Normally I would create a singleton for this purpose so all modules access the same state of the DeviceManager
.
To create a singleton I use:
class DevicesManagerInstance {
constructor() {
this.devices = {};
}
addDevice(id, device) {
this.devices.id = device;
}
}
let DevicesManagerInstance = new DevicesManager();
module.exports = DevicesManagerInstance;
I've found some older questions regarding singletons and sharing data but still not satisfied with the answer to the question if it is de NodeJS way to share data:
But also read singletons are an anti-pattern. Can someone clarify what is the "NodeJS" way of sharing data between modules (in my case the devices). In Angular I would create a service for this purpose.
Upvotes: 2
Views: 6254
Reputation: 3184
This is a single instance but if you need class you can also convert the following to class structure easily,
var DeviceManager = function() {
this.devices: []; // constructor
};
DeviceManager.prototype.addDevice = function(id, device) {
DeviceManager.devices[id] = device;
};
var deviceManager = new DeviceManager();
module.exports = deviceManager;
You can access the devices in other modules as
var DeviceManager = require('./devicemanager');
DeviceManager.devices; // accessing devices
Upvotes: 2
Reputation: 2113
Why fix what isn't broken? If your approach works, it works.
That being said, I don't see any reason to create a class if I'm only going to create one instance. I would opt for a different approach:
var DeviceManager = {
devices: {},
addDevice(id, device) { // this is valid syntax
DeviceManager.devices[id] = device;
}
};
module.exports = DeviceManager;
or, if you don't want devices to be available outside of the module:
var devices = {};
var DeviceManager = {
addDevice(id, device) { // this is valid syntax
devices[id] = device;
}
};
module.exports = DeviceManager;
Upvotes: 4