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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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” :

1
2
3
4
5
6
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 !

Copy from http://simplapi.wordpress.com/2012/05/14/node-js-singleton-structure/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s