On gists
Decorator
JS Patterns
decorator.js
Raw
#
/*
URL: https://learn.coderslang.com/0116-javascript-design-patterns-decorator/
*/
class Headphone {
constructor(model, color) {
this.model = model;
this.color = color;
}
getPrice() {
return 100;
}
}
class WirelessHeadPhone extends Headphone {
constructor(model, color) {
super(model, color);
this.isWired = false;
}
getPrice() {
return 150;
}
}
class WaterproofHeadPhone extends Headphone {
constructor(model, color) {
super(model, color);
this.isWaterproof = true;
}
getPrice() {
return 120;
}
}
class WaterProofAndWirelessHeadphone extends Headphone {
constructor(model, color) {
super(model, color);
this.isWaterproof = true;
this.isWired = false;
}
getPrice() {
return 170;
}
}
class BabyEarHeadphone extends Headphone {
constructor() {
super(model, color);
this.size = 'Small';
}
getPrice() {
return 80;
}
}
decorator-2-example.js
Raw
#
class CupCake {
constructor(flavour, color) {
this.flavour = flavour;
this.color = color;
this.cost = 3;
}
}
//decorator 1
const addSprinkles = function(cupcake) {
const cost = cupcake.cost + 1;
return {...cupcake, hasSprinkles: true, cost};
}
//decorator 2
const addSkittles = function(cupcake) {
const cost = cupcake.cost + 2;
return {...cupcake, hasSprinkles: true, cost};
}
const vanilla = new CupCake('vanilla', 'blue');
const sprinkledVanilla = addSprinkles(vanilla);
const skittleVanilla = addSkittles(vanilla);
const fullDecoratedVanilla = addSkittles(sprinkledVanilla); //A combination of both sprinke decorator and skittle decorator.
console.log(vanilla.cost); //3
console.log(sprinkledVanilla.cost); //4
console.log(skittleVanilla.cost); //5
console.log(fullDecoratedVanilla.cost); //5