NodeJS patterns — The decorator pattern
While learning about NodeJS design patterns I went through many useful techniques, but one that I think is really interesting is the decorator pattern.
The Decorator Pattern allows us to attach additional properties and methods to existing objects.
For example, instead of creating a new class that will produce an upgraded one, we can create a decorator class that will have the desired properties and methods.
Let’s build a Shopper class, which will have a constructor and will have
nameis the name of the instance
accountis the amount of money owed by the instance
itemsis an array with objects bought by the instance
The shopper will have a
purchase() method which will check if the instance has enough money to buy the item and if it does it will take the item price off the account and will add the item in the
The shopper will also have a
printStatus() method which will print in the console all the details about the instance.
Now we need an item so our shopper can purchase. Let’s creates a class
InventoryItem which will be constructed by a
name and a
price , and will have
Now if we create an
index.js and create a new shopper, for example
alex and a new item
necklace, Alex can purchase the item.
Now is the interesting part.
Let’s create a class that will decorate our necklace item and transform it into a Golden Item.
We need to create a class
GoldenInventoryItem that will receive in the constructor an instance of a
Now we can create a
golden_necklace and let Alex purchase it.
And our result will be:
Our Golden Necklace was purchased and it’s expensive.
I consider the decorator pattern a useful and easy way to improve any class that may need any additional methods or properties. It can transform a simple necklace into a golden one which looks like a very powerful tool, also.