Created
September 13, 2020 08:55
-
-
Save misterpoloy/e95e86b41ac84491385d159adb3ed846 to your computer and use it in GitHub Desktop.
Factory Pattern Example
This file contains hidden or 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
class IceCreamFactory { | |
constructor() { | |
this.createIcecream = function(flavor) { | |
let iceCream; | |
if (flavor === 'chocolate'){ | |
iceCream = new Chocolate(); | |
} | |
else if (flavor === 'mint'){ | |
iceCream = new Mint(); | |
} | |
else if (flavor === 'strawberry'){ | |
iceCream = new Strawberry(); | |
} | |
return iceCream; | |
}; | |
} | |
} | |
class Chocolate { | |
constructor() { | |
this.icecreamFlavor = "chocolate"; | |
this.message = function() { | |
return `You chose the ${this.icecreamFlavor} flavor.`; | |
}; | |
} | |
} | |
class Mint { | |
constructor() { | |
this.icecreamFlavor = "mint"; | |
this.message = function() { | |
return `You chose the ${this.icecreamFlavor} flavor.`; | |
}; | |
} | |
} | |
class Strawberry{ | |
constructor() { | |
this.icecreamFlavor = "strawberry"; | |
this.message = function() { | |
return `You chose the ${this.icecreamFlavor} flavor.`; | |
}; | |
} | |
} | |
// creating objects | |
const iceCreamfactory = new IceCreamFactory(); | |
const chocolate = iceCreamfactory.createIcecream('chocolate'); | |
const mint = iceCreamfactory.createIcecream('mint'); | |
const strawberry = iceCreamfactory.createIcecream('strawberry'); | |
console.log(chocolate.message()); | |
console.log(mint.message()); | |
console.log(strawberry.message()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment