Last active
August 29, 2015 14:13
-
-
Save jvmvik/958775a5673e32e68194 to your computer and use it in GitHub Desktop.
Singleton pattern implemented in NodeJS. Example: Shared database like neDB or MongoDB, Application configuration, Filter...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
* NodeJS module that implements the single pattern. | |
* http://en.wikipedia.org/wiki/Singleton_pattern | |
* | |
* The goals is to create the object: instance only one time | |
* thus the instance is shared in the source code. | |
* | |
* You must be aware that there is a risk to break | |
* the isolation principles. | |
*/ | |
if(!global.instance) | |
{ | |
var instance = {}; | |
instance.state = false; | |
instance.func1 = function(state){ | |
instance.state = state; | |
}; | |
global.instance = instance; | |
} | |
exports.instance = global.instance; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
* Test singleton instance. | |
* | |
* - File must be created under directory: test/ | |
* - Depedencies | |
* $npm install mocha expect | |
* - Run tests. | |
* $mocha | |
*/ | |
var expect = require('expect'); | |
describe("Singleton", function() | |
{ | |
it("Implementation", function() | |
{ | |
// Check default state | |
expect(require('../Singleton').instance.state).toBe(false); | |
// Change the state of the instance (shared everywhere) | |
require('../Singleton').instance.func1(true); | |
// Check if the new state has been propagated to the instance itself | |
expect(require('../Singleton').instance.state).toBe(true); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment