Decorator Design Pattern
--
Hey, I’m back with a new design pattern.
It is used when you:
- Need to add additional functionality/responsibility to an object dynamically.
- Need to remove functionality/responsibility from an object.
- Want to avoid too many sub-classes for adding additional functionality/responsibility.
Let’s take an example of everyone’s favorite Pizza shop. Suppose we want to create a pizza ordering application using which we can order different types of pizza like onion, sweet corn, and capsicum. We want to calculate the cost of each type of Pizza for now.
So we can proceed like this. For Pizza, we can either go with the interface or abstract class.
Now customers are asking for extra cheese and sauce with Pizza. Now we need to incorporate these changes as well.
Now one way of achieving the same is to create a concrete class for each type of pizza and every class will be implementing the cost method.
It looks like a class explosion. Isn’t it?
One more way to implement the same. Like we can have some boolean variable in the Pizza class itself, that will define if the customer wants extra cheese/sauce or not. Code for the same will look like this.
Now getCost() method is not abstract, although every subclass can implement it and will use this method to calculate the final cost of the Pizza.
Now, what if the customer wants 2 or 3 units of extra sauce. And also, we have broken the open-closed principle. Suppose in the future we want to add another condiment, then we need to modify the Pizza class itself.
Open-Closed Principle: Classes should be open for extension, but closed for modification.
Now, It is the right time to introduce the decorator pattern.
Definition: The Decorator Pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Now we will not be modifying our current classes(Pizza, OnionPizza, SweetCornPizza, CapsicumPizza) that we have taken in the beginning. Let’s see how we can add all these condiments.
So these two condiments classes we added, that’s it.
Let’s see the driver class now.
So, look like we decorate our pizza with sauce and cheese. Isn’t quite interesting?
Here is the output:
Reference: Head First design pattern
If you like this article, you can click on the clap button to appreciate me and share it with your friends, if you didn’t like this, unfortunately, we don’t have a dislike button here. If you have any thoughts to share, you can share in the comment section or you can inbox me at hunnychawla528@gmail.com.