easy-factory
v1.3.0
Published
Simple base class for a consistent factory pattern.
Downloads
884
Readme
This module will help you to have consistent implementations of the abstract factory pattern.
Extend the Factory base class in your own factory and implement the getClass static method with your business logic.
Example
This is the example in the tests.
'use strict';
const Factory = require('easy-factory');
/* eslint-disable global-require */
/**
* @classdesc
* A factory class to get a fruit.
*
* @class FruitFactory
*/
class FruitFactory extends Factory {
/**
* Decide which fruit to instantiate based on the size and sugar.
*
* @param {object} context
* Contains the keys: 'size' and 'sugar'.
*
* @throws Error
* If no fruit could be found.
*
* @return {function}
* The fruit to instantiate.
*/
static getClass(context) {
if (typeof context.size === 'undefined' || typeof context.sugar === 'undefined') {
throw new Error('Unable to find fruit.');
}
if (context.size >= 5) {
// This is a big fruit.
return context.sugar >= 5 ? require('./mango') : require('./pumpkin');
}
return context.sugar >= 5 ? require('./grape') : require('./almond');
}
}
module.exports = FruitFactory;
Use it:
const fruit = FruitFactory.create({size: 10, sugar: 10}, 'constructor argument');
console.log(fruit.name());
// Outputs 'Mango'.