Intent
It allows us to dynamically add behaviour or a new functionality to an individual object, without affecting the behaviour of the other objects of the same class. We can imagine it like as if we were wrapping a gift, putting it in a box, and then wrapping the box.
Problem
Imagine that we have a subscription service such that every time an article this one gets posted the subscriber gets notified on his/her email, now imagine that some users prefer to be notified via SMS, and others on Twitter, and It keeps growing.
then what should we do as adding these functionalities would require some effort and may get more complex?
Solution
I bet you that you thought that the best thing, in this case, is to use inheritance, but actually, that would be wrong as, In most programming languages, inheritance won't let a class inherit behaviours of multiple classes at the same time.
and inheritance won't let us alter the behaviour of an existing object at runtime as it is static.
Here comes the role of the decorator design pattern!
An object can use the behaviour of various classes that change the behaviour of the container at runtime, having references to multiple objects and delegating them all kinds of work.
Pros and Cons
Pros
- We can combine several behaviours by wrapping an object into multiple decorators.
- We can expand a function of classes without inheritance.
- We will be able to remove and add responsibilities to an object at runtime.
Cons
- It results in a high number of objects.
- It is hard to remove a specific wrapper from the wrapper's stack. So it may not be beginner friendly.
Thank you, and goodbye.