Node.JS Singleton structure

I was searching using a singleton to create a kind of garbage class which allow me to create a multi room chat easily by manually connecting socket into room (with socket.io).

Here is a basic singleton module I create to do shared garbage space :

var singleton = function singleton(){
	//defining a var instead of this (works for variable & function) will create a private definition
	var socketList = {};

	this.add = function(userId, socket){
		if(!socketList[userId]){
			socketList[userId] = socket;
		}
	};

	this.remove = function(userId){
		if(socketList[userId]){
			delete socketList[userId];
		}
	};

	this.getSocketList = function(){
		return socketList;
	};

	if(singleton.caller != singleton.getInstance){
		throw new Error("This object cannot be instanciated");
	}
}

/* ************************************************************************
SINGLETON CLASS DEFINITION
************************************************************************ */
singleton.instance = null;

/**
 * Singleton getInstance definition
 * @return singleton class
 */
singleton.getInstance = function(){
	if(this.instance === null){
		this.instance = new singleton();
	}
	return this.instance;
}

module.exports = singleton.getInstance();

Here I create a really basic singleton class which allow to add or remove socket in an object-map.
I export directly the getInstance, which allow to directly manipulate object like that (assuming the code above is stored in a file « singleton.js » :

var sg = require("./singleton.js");
var sg2 = require("./singleton.js");
sg.add(1, "test");
sg2.add(2, "test2");

console.log(sg, sg2);

As you can see, both sg and sg2 got same list of id stored which is composed of 1 => test and 2 => test2, here is a screenshot :
node.js singleton

Enjoy playing with singleton to share data between module !

About these ads

7 Commentaires

  1. Just what i was looking for. A++

  2. Patrick

    This is awesome. I have been struggling with this for quite some time and this solution is simple and elegant. Thank you very much.

  3. JeyDotC

    This article have been very useful, it helped me to answer this question at stackOverflow: http://stackoverflow.com/questions/12487416/example-express-app-that-uses-sequelize

    I’d add just one thing: A skelton form of your singleton module.

  4. Pingback: singleton pattern in nodejs – is it needed? | Jisku.com

    • deisss

      Load 2 times the same object, i got different result (v0.6), so I would say yes singleton pattern is needed in some cases. But the singleton pattern is of course not to be used in most of cases ! Application of it in Node.JS are almost the same : a memory store…

  5. Singletons are not needed for node.js. A much more simple approach is:
    //singleton.js
    var socketList = {};
    exports.socketList = socketList;
    exports.add = function(userId, socket) {
    if (!socketList[userId]) {
    socketList[userId] = socket;
    }
    };
    exports.remove = function(userId) {
    if (socketList[userId]) {
    delete socketList[userId];
    }
    };

    //testsingleton.js
    var util = require(‘util’);
    var sg = require(« ./singleton.js »);
    var sg2 = require(« ./singleton.js »);
    sg.add(1, « test »);
    sg2.add(2, « test2″);
    sg.remove(1);
    sg.add(3, « test3″);

    console.log(« sg.socketList: » + util.inspect(sg.socketList));
    console.log(« sg2.socketList: » + util.inspect(sg2.socketList));

Laisser un commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l'aide de votre compte WordPress.com. Déconnexion / Changer )

Image Twitter

Vous commentez à l'aide de votre compte Twitter. Déconnexion / Changer )

Photo Facebook

Vous commentez à l'aide de votre compte Facebook. Déconnexion / Changer )

Photo Google+

Vous commentez à l'aide de votre compte Google+. Déconnexion / Changer )

Connexion à %s

Suivre

Recevez les nouvelles publications par mail.

%d blogueurs aiment cette page :