Skip to content

Instantly share code, notes, and snippets.

@drenther
Last active November 29, 2018 23:30
Show Gist options
  • Save drenther/f69f836ee8403dca1fb562485ddade8d to your computer and use it in GitHub Desktop.
Save drenther/f69f836ee8403dca1fb562485ddade8d to your computer and use it in GitHub Desktop.
Structural Pattern - Flyweight
// 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