ruk·si

🍦 JavaScript Pattern
Factory

Updated at 2015-05-13 16:10
var Sword = (function() {
  'use strict';
  var Sword = function(options) {
    options = options || {};
    this.price = options.price || 5;
    this.material = options.material || 'iron';
    this.damage = options.damage || 5;
  };
  return Sword;
}());

var Shield = (function() {
  'use strict';
  var Shield = function(options) {
    options = options || {};
    this.price = options.price || 3;
    this.material = options.material || 'iron';
    this.defense = options.defense || 5;
  };
  return Shield;
}());

var Blacksmith = (function() {
  'use strict';
  var Blacksmith = function(options) {
    this.smithingItem = options.defaultItem;
  };
  Blacksmith.prototype.createItem = function(options) {
    options = options || {};
    if (options.itemType === 'sword') {
      this.smithingItem = Sword;
    }
    if (options.itemType === 'shield') {
      this.smithingItem = Shield;
    }
    return new this.smithingItem(options);
  };
  return Blacksmith;
}());

var eric = new Blacksmith({
  defaultItem: Sword
});

var sword1 = eric.createItem();
console.assert(sword1 instanceof Sword);
console.assert(sword1.material === 'iron');

var shield1 = eric.createItem({
  itemType: 'shield'
});
console.assert(shield1 instanceof Shield);

var sword2 = eric.createItem({
  itemType: 'sword',
  material: 'steel'
});
console.assert(sword2 instanceof Sword);
console.assert(sword2.material === 'steel');