easy-factory

1.3.0 • Public • Published

Build Status Coverage Status Known Vulnerabilities semantic-release Greenkeeper badge

NPM

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'.

Readme

Keywords

Package Sidebar

Install

npm i easy-factory

Weekly Downloads

151

Version

1.3.0

License

GPL-2.0

Last publish

Collaborators

  • e0ipso