Last active
August 29, 2015 14:13
-
-
Save gregstewart/74573eea38adc51c1ee6 to your computer and use it in GitHub Desktop.
Different factory patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ObjectFactory () { | |
this.build = { | |
chocolate: function () { | |
console.log('built a chocolate factory'); | |
}, | |
fudge: function () { | |
console.log('built a fudge factory'); | |
} | |
} | |
} | |
function SwitchCaseFactory () { | |
this.build = function (type) { | |
var factory; | |
switch (type) { | |
case 'chocolate': | |
factory = function () { | |
console.log('built a chocolate factory'); | |
}; | |
break; | |
case 'fudge': | |
factory = function () { | |
console.log('built a fudge factory'); | |
}; | |
break; | |
} | |
return factory() | |
} | |
} | |
var objectFactory = new ObjectFactory(); | |
objectFactory.build.chocolate(); | |
var switchCaseFactory = new SwitchCaseFactory(); | |
switchCaseFactory.build('fudge'); | |
function Chocolate () { | |
console.log('built a chocolate object'); | |
} | |
function Fudge () { | |
console.log('built a fudge object'); | |
} | |
function SweetFactory () { | |
function classFor (type) { | |
switch (type) { | |
case 'chocolate': | |
return Chocolate; | |
case 'fudge': | |
return Fudge; | |
} | |
} | |
this.build = function (type) { | |
var Sweet = classFor(type); | |
return new Sweet(); | |
} | |
} | |
var sweetFactory = new SweetFactory(); | |
sweetFactory.build('chocolate'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment