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 a popular design pattern that you may have heard. It is called the Prototype Pattern.
Have you ever had the problem where you have one specific object that you want to duplicate to an exact same copy? The "easy" way would be to just generate a new object with the same values over and over, but, some of those objects could have some private or protected fields that you’ll miss...
Also, it’s quite ugly 🤨
Feeling like you really need to get rid of this problem? Then you have to choose the Prototype Pattern, where you will create a prototype that can be cloned with just a single method.
This one is pretty easy. You just have to generate one, two, or as many variants as you need, and, when you need an exact same object, you just clone it!
In the next diagram created by refactoring guru, you'll see how there is defined a Prototype interface. It will specify the kinds of objects to create using the subsequent prototypes, and create new objects by copying this prototype.
Things you need to have in mind when working with prototypes:
- Use only if your code shouldn’t depend on the subclasses of objects that you need to copy.
- Try to use it only when you have many subclasses that they are only differentiated by the way they are initialized.
If you follow the ideas raised above, you will have an amazing factory of prototypes ready to be tested.
Now, your clones production will be ✨ clean and efficient ✨
And this is my fourth 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!