Skip to content

Commit

Permalink
The Decorator pattern
Browse files Browse the repository at this point in the history
We add a class GoldenInventoryItem, and a class DiamondInventoryItem. So
for GoldenInventoryItem, we have to give it a constructor, and the
constructor takes in the baseItem. And what we're going to do is we're
going to add to the existing baseItem. So we take the baseItem name, and
we extend it by adding the word Golden in front of it. We also take the
price of the item, so whatever the baseItem price is, we just add 1000
to that. So we are extending the baseItem. We do the same thing with the
DiamondInventoryItem. But decorators do not have to match the exact same
interface, they don't have to have the exact same fields and methods
that our baseItem has. We can actually add more functionality. For
instance, the Diamond can cut glass. So this.cutsGlass is equal to true.
We can also overwrite or modify any of the methods. So when we print the
diamond, we do something a little different, we console log this.name
costs a lot of money. So these items are decorators. They take in a base
item, or a base class, and they extend its functionality. In this case,
we add some more to the price. We change the description of the item.
And in the case of the DiamondInventoryItem, we've overwritten the print
method.
  • Loading branch information
diegomais committed Jun 1, 2020
1 parent d9f99da commit 6e151ab
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
21 changes: 20 additions & 1 deletion decorator-pattern/InventoryItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,23 @@ class InventoryItem {
}
}

module.exports = InventoryItem;
class GoldenInventoryItem {
constructor(baseItem) {
this.name = `Golden ${baseItem.name}`;
this.price = 1000 + baseItem.price;
}
}

class DiamondInventoryItem {
constructor(baseItem) {
this.name = `Diamond ${baseItem.name}`;
this.price = 1000 + baseItem.price;
this.cutsGlass = true;
}

print() {
console.log(`${this.name} costs a lot of money...`);
}
}

module.exports = { InventoryItem, GoldenInventoryItem, DiamondInventoryItem };
8 changes: 5 additions & 3 deletions decorator-pattern/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ var {
DiamondInventoryItem,
} = require("./InventoryItem");

var alex = new Shopper("Alex", 100);
var alex = new Shopper("Alex", 4000);

var walkman = new InventoryItem("Walkman", 29.99);
var necklace = new InventoryItem("Necklace", 9.99);
Expand All @@ -15,7 +15,9 @@ var diamond_gold_necklace = new DiamondInventoryItem(gold_necklace);

var diamond_walkman = new DiamondInventoryItem(walkman);

alex.purchase(necklace);
alex.purchase(walkman);
alex.purchase(diamond_gold_necklace);
alex.purchase(diamond_walkman);

alex.printStatus();

diamond_walkman.print();

0 comments on commit 6e151ab

Please sign in to comment.