jeudi 2 avril 2015

How to build a nodeJS factory?

After reading examples online on creating module and design patterns like:


http://ift.tt/1se9jxu


http://ift.tt/1xEq87A


I am not able to decide which pattern is better. At the moment, I am using a singleton pattern. Is it the correct implementation?


Essentially I want to encapsulate different modules into a factory and return an object.


Each modules has its own config.


moduleA.js



var moduleA = function(config) {
this.wheels = config.wheels || 4;
this.display = function() {
console.log('wheels: '+this.wheels);
}
};
module.exports = moduleA;


moduleB.js



var moduleB = function(config) {
this.wheels = config.wheels || 8;
this.display = function() {
console.log('wheels: '+this.wheels);
}
};
module.exports = moduleB;


factory.js



var moduleA = require('./moduleA');
var moduleB = require('./moduleB');

var factory = function(config){
this.moduleClass = function(){};
switch(config.type){
case 'a' : this.moduleClass = moduleA; break;
case 'b' : this.moduleClass = moduleB; break;
}
return new this.moduleClass(config);
};
module.exports = factory;


Calling it should be something like :



var config = {type:'a', wheels: 4};
var myFactory = require('./factory')(config);
myFactory.getModuleA();
config = {type:'b', wheels: 8};
myFactory.setConfig(config);

Aucun commentaire:

Enregistrer un commentaire