Factory Pattern
Short Def: Used to encapsulate the creation logic for a related family of
objects.
Long Def: Used commonly to simplify object creation in systems where numerous similar objects are
dynamically created based on a few differing properties. The pattern takes redundant
object creation code that might be scattered throughout a system and wraps that
code in a single object in a reusable form that can be used across the system.
Another key attribute of this pattern is that the factory encapsulates the logic
needed to create objects of different types based on the arguments provided. This
removes the need for the caller to be concerned with specifying the object type
needed and it therefore relies on the factory to provide what it needs.
Script: Supplemental for Example Below
// Constructor functions that will be used inside of the Lizard Factory function Lizard(kind, moves) { this.kind = kind; this.moves = moves; } Lizard.prototype.bites = function() { console.log(`${this.kind} just bit me really hard as it ${this.moves} away.`); }; Lizard.prototype.says = function() { console.log(`I am a ${this.kind}.`); }; function Chameleon(name, moves) { Lizard.call(this, 'Chameleon', moves); this.name = name; this.color = 'green' } Chameleon.prototype = Object.create(Lizard.prototype); Chameleon.prototype.changeColor = function(color){ this.color = color; console.log(`${this.kind} just changed color to ${this.color}, you no see me!`); }; function Dragon(name, moves) { Lizard.call(this, 'Dragon', moves); this.name = name; } Dragon.prototype = Object.create(Lizard.prototype); Dragon.prototype.fireBreath = function(){ console.log(`${this.kind} breath, you are now on fire.`); };
Script: Factory Example
// Lizard Factory: setup to select the appropriate object type to create // based on a keyword passed in followed by an arguments array that is // passed to the appropriate object constructor function. let LizardFactory = function(){ this.create = function(type, args){ switch(type){ case 'chameleon': return new Chameleon(...args); case 'dragon': return new Dragon(...args); default: return new Lizard(...args); break; } }; }; let factory = new LizardFactory(); let baseLizard = factory.create(null, ['base lizard', 'speedy little demon']); console.log(baseLizard); let myChameleon = factory.create('chameleon', ['Freddy', 'very very slow']); myChameleon.changeColor('red'); console.log(myChameleon); let myDragon = factory.create('dragon', ['Freddy', 'very very slow']); myDragon.fireBreath(); console.log(myDragon);
Published by