puretuts-object-singleton-factory v0.1.0
puretuts-object-singleton-factory
Shows how to leverage singleton and factory module patterns in Node.js. A common object is defined, then it is require()'ed into the program in several ways to demonstrate object, singleton and factory patterns in Node.js.
I genuinely hope this becomes the simplest, cleanest and most easy-to-understand tutorial on the subject topics. If it isn't, or if I can make it better, please let me know.
Table of Contents
Installation
$ npm install puretuts-object-singleton-factory
Examples
This is a simple tutorial designed to quickly show you how to define Node.js/CommonJS modules that export an object, a singleton and a factory. By using each of these patterns correctly, you can have enormous levels of flexibility in your Node.js application code base.
Object Pattern
The goal is to define a Node.js module that simply exports an object. When the module is require()'ed into an application, the application should be able to create object instances intuitively without weird syntax at all.
function TheObject (options) {
this.options = options;
}
TheObject.prototype.showOptions = function ( ) {
console.log('my options:', this.options);
};
module.exports = exports = TheObject;
Singleton Pattern
The goal is to define a Node.js module that will return the same object instance any time it is require()'ed into an application even if more than one module includes the singleton across the whole application. Thanks to Node's module caching behavior, this is incredibly simple to achieve:
var TheObject = require('./the-object');
var theInstance = new TheObject({
'mode': 'singleton',
'message': 'I am the singleton instance created at ' + (new Date()).toString()
});
module.exports = exports = theInstance;
Factory Pattern
The goal is to define a Node.js module that exports a function that, when called, will create a new instance of TheObject configured as desired. The factory function will simply create a new instance passing in the specified options and return the instance.
var TheObject = require('./the-object');
module.exports = exports = function (options) {
var instance = new TheObject(options);
return instance;
};
About PureTuts
PureTuts is something new I'm trying. There are, in my opinion, two effective approaches to teaching programming:
- Just show me how; and
- Get out of my way and let me teach myself.
This is a blend of the two. I will show you the MOST basic way to do something. Then, you can start exploring, experimenting, etc. And, if you take it further, fork the tut and add to it on your own. In other words: Take a puff, then pass it to someone else. Should be familiar enough in this field.
I only hope these tutorials help someone out there learn these concepts. Period. Because this (code by dissection, etc.) is how I learn and how I teach. Not for you? Great! Leaves more for others.
11 years ago