Decorator
Decorator Design pattern is part of Structural Patterns from Gang of Four (GoF) Design patterns. It is a widely used structural pattern. It dynamically adds the functionality to an object at runtime without affecting the other objects. It adds further answerability to an object by bundling it.
According to GoF,
The Gang of Four (GoF) at Dofactory states - "
Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."
For example, egg omelet is an object which is already cooked and acknowledged as a primary object. As per the customer request, we need to add some optional toppings like sauce and onion to it, the primary is only for the object the customer requested without affecting other omelets. We can acknowledge these toppings as an optional responsibility added by the decorator.
Important Points to Remember
Add and remove optional functionalities to an object actively at runtime without affecting the other objects.
Generally, these decorators are designed on the component interface, so we can select the object which has to be decorated at runtime.
Many times adding an extra responsibility to a class may not be possible by making it a child class. The only available way of achieving it is by using decorator.
Following are the parts of the decorator design pattern,
- Component - Omelet is the base interface
- Concrete component- A normal baked omelet is the material implementation of the omelet interface
- Decorator- It is the abstract class which holds the reference of the component and implements from the component.
- Concrete Decorator- Whoever implements from the abstract decorator and adds extra responsibility to a concrete component.