A pattern a day keeps the reviewers away - [Day 3] - Decorator Pattern
Antonio Djigo
Posted on February 13, 2020
Hey 👀✨
During the past few months, I've been working on a back-end project made with Ruby on Rails. Last year I was working as a Front-End developer, I've never had the opportunity to apply design patterns almost anywhere, until now.
It's a pretty useful thing, that probably every developer that works with objects should at least know and practice, and this is why I'm here, to give you (and me!) a daily short post about the different design patterns that exist (or at least, those that are used the most), with an example, and an explanation.
Because doing good code will help you, your workmates, and those who will be in the future.
Today, I'll write about another pattern that you'll spot almost in every project. It is called Decorator Pattern.
You may have had the problem of having an object with a lot of possible functionalities or states. This object is already a mess, so we don't want to alter its structure, or making the class even fatter.
If you want to get rid of problems like this, you'd choose the Decorator Pattern, where you will create a class wrapping your original object to provide additional functionality without modifying our main class.
To generate a decorator object, you have to create a new class. Inside this new class, you will then define all the extra functionality that may be used in your object, let's call it Christmas tree.
Once you are writing your Christmas tree view or controller, you would call, for example, your golden star to add it on top of your adorable tree.
Let me explain the example before you read it. We will now create a Christmas tree, and, next to it, we will create two different decorators that will serve us everything we need to have an awesome tree.
Things you need to have in mind when working with decorators:
- Ensure the context is: a single component, several optional embellishments, and an interface that is common to all.
- All classes should be interchangeable and/or mixable.
Now, in our AwesomeChristmasTree, we can decorate it by calling the inherited methods from our decorators!
Another example for you to understand could be this one, created by refactoring guru website:
Now, your tree would be decorated ✨ clean and efficiently ✨
And this is my third article about design patterns for the series "A pattern a day keeps the reviewers away".
I'll try to keep posting every day one of the different patterns that are around. I can't promise I'll fulfil this task every day though!
You can read more about this pattern at:
Also, you can follow me so you are tuned to whenever I post something through my Twitter account!
Posted on February 13, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 14, 2020
February 11, 2020