Decorator Design Pattern
The Decorator Design Pattern is a structural pattern that adds or extends funcionality of an object at runtime by wrapping it in a Decorator class without altering the original object.
This allows to add new functionality and prevents breaking existing ones.
This supports the Open Closed Principle.
Component: It’s the base class for concrete components as well as for the Decorator class. It could also be an interface.
Concrete Component: This is the object to which new functionalities can be attached.
Decorator: It’s the base class for all concrete component decorators and it inherits from the base component and will hold a parameter in its constructor of type component. That’s the object that will be wrapped.
Concrete Decorators: They will add new functionalities/responsabilities to the component
The following is a classic example. Let’s say we have a pizza company that sells 3 types of pizza as shown on the image
Some time later, we notice customers like to add toppings like ham, cheese and peppers which will increase to cost of each pizza. So we need to modify our design.
The following design could work but it would be very hard to mantain
Here is where Decorator Design Pattern comes in handy and the design will look like this
As it can be seen Cheese, Ham and Peppers will “decorate” the pizza class so any combination can be done and each will implement the CalculateCost method adding it to the component received in its constructor.
The base scenarios where this pattern can be used are:
- Legacy Systems.
- Add funcionality to UI controls.
- Sealed classes from a third party.