Decorator Design Pattern
Decorator / Wrapper is one of the most heavily used structural design pattern. You might have also come across it many times. In this article we will understand what is Decorator pattern and how it's implemented.
Consider that you are working on an image sharing application that reads from and writes images to the storage.
This is what the code looks like:
However later on you also want to give your users additional features like encryption/decryption, compression/decompression, renaming, beautification etc.
Now you can extend the image class to create these different types of images and write logic to perform these manipulations in the extended classes. Then depending upon the type of image (compressed, cropped, encrypted etc.) you can choose one of these extended classes. But some users might want to do multiple of these operations together - compression with encryption or maybe beautification, compression and cropping together etc. Now you'll have to create classes for all different combinations of these actions (image below). Soon, the number of classes created would explode. Addition of any new actions would mean a LOT of developer efforts.
Recommended by LinkedIn
What now?
We can make use of the Decorator pattern which suggests that we create a class and make it extend the wrappee, image here (or the parent interface of wrappee). Now our class can be used as an wrapee (image). Next we aggregate the wrappee object (or the parent interface of wrappee) inside our class. Our class then performs the required operation and then delegates the saving/retrieval logic to the parent class.
Here is what the implementation looks like
We can see that this saves us a lot of developer efforts. Different decorators can also be plugged in at any time in the code without any required modifications in the code. This makes the code open for extension but closed for modification. The decorators can also be chained without the need to create any new classes. This pattern also breaks responsibility to multiple classes compared to one big class handling everything.
I took help from the following sources to write this article:
Hope you liked this article. I regularly write such short articles on LinkedIn. Follow Prateek Mishra and learn something new everyweek.
Great example !