NodeJS patterns — The decorator pattern

Zaharia Anton
2 min readMar 4, 2021

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 name , account and items properties.

  • name is the name of the instance
  • account is the amount of money owed by the instance
  • items is 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 items array.

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 print method which will print the details of the item.

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 InventoryItem.

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.

Conclusion

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response