e0ipso / easy-factory

Simple base class for a consistent abstract factory pattern.
GNU General Public License v2.0
1 stars 0 forks source link
design factory patterns

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