Last active
November 29, 2018 23:30
-
-
Save drenther/f69f836ee8403dca1fb562485ddade8d to your computer and use it in GitHub Desktop.
Structural Pattern - Flyweight
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
// flyweight class | |
class Icecream { | |
constructor(flavour, price) { | |
this.flavour = flavour; | |
this.price = price; | |
} | |
} | |
// factory for flyweight objects | |
class IcecreamFactory { | |
constructor() { | |
this._icecreams = []; | |
} | |
createIcecream(flavour, price) { | |
let icecream = this.getIcecream(flavour); | |
if (icecream) { | |
return icecream; | |
} else { | |
const newIcecream = new Icecream(flavour, price); | |
this._icecreams.push(newIcecream); | |
return newIcecream; | |
} | |
} | |
getIcecream(flavour) { | |
return this._icecreams.find(icecream => icecream.flavour === flavour); | |
} | |
} | |
// usage | |
const factory = new IcecreamFactory(); | |
const chocoVanilla = factory.createIcecream('chocolate and vanilla', 15); | |
const vanillaChoco = factory.createIcecream('chocolate and vanilla', 15); | |
// reference to the same object | |
console.log(chocoVanilla === vanillaChoco); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment