Skip to content

Instantly share code, notes, and snippets.

@zoe-1
Last active August 29, 2015 14:18
Show Gist options
  • Save zoe-1/d5465682428edc583ccc to your computer and use it in GitHub Desktop.
Save zoe-1/d5465682428edc583ccc to your computer and use it in GitHub Desktop.
Modules & Singleton
// ./lib/index.js
// ./test/index.js
// Both files above make an object with require module as below.
var Version = require('./lib/version');
// Version modified in ./test/index.js
Version.register = function (server, options, next) {
next('Break plugin');
};
// Changes are seen in Version object of different file ./lib/index.js
// How??
@zoe-1
Copy link
Author

zoe-1 commented Apr 3, 2015

The singleton nature of node.js required modules is really important to understand.
According to @hueniverse, "required modules are particularly important because they represent a singleton object shared with the entire application". Assignment3 illustrates how required modules in
node.js are important, powerful, and a bit confusing when coming from another object oriented language.
source @hueniverse's Simple node.js code style tips to improve code quality

Assignment3's Use of JS Singleton Design
When completing assignment3 we utilized the singleton nature of node's required modules when running tests. In short, both, ./lib/index.js and ./test/index.js create their own Version objects in separate places. However, they both contain the same value all the time. It is as if their values are synchronized. But, in reality they are just referring to the same object. This illustrates node's require modules singleton design pattern.

Singleton Objects Made Using Required Modules

var Version = require('../lib/version');

The above syntax can be used to create objects by requiring modules anywhere in the project.
Because of node's singleton pattern design the objects made from the same module will have the
same value throughout the project. They are singleton objects.

View ./test/index.js
View ./lib/index.js
Notice how ./test/index.js modifies the version object and the results of the modifications are
seen in ./lib/index.js Version object. This is because any object created by node's require('module_file') returns a reference to the same object.

var Version = require('../lib/version');

This is the node.js require module singleton design pattern in action.

What is a Singleton Pattern?

The singleton pattern is implemented by creating a class with a method that creates a new instance of
the class if one does not exist. If an instance already exists, it simply returns a reference to that
object. To make sure that the object cannot be instantiated any other way, the constructor is made private.

source Wikipedie Singleton Pattern

Further Reading

Node.js Singleton Docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment