The decorator pattern is a common design pattern often used to add new functionality to an object dynamically. The main benefit of the decorator pattern is that the existing object’s class is not directly modified. This follows the open-closed principle in the Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion design principles, or SOLID for short.
The four participants are:
- Component Interface:: Interface for the objects that can have responsibilities added to it dynamically. The component interface defines the operations and properties for the component. In our example ICreditCard
- ConcreteComponent: Defines an object implementing Component interface. This is the object that is going to be decorated, but it doesn’t have any knowledge of decoration. The person implementing the decorator may not even have the access to the source code. The concrete component is the primary class you want to extend that implements the component interface. In our example CreditCard.
- Decorator: Maintains a reference to the Component object, and defines an interface that conforms to the Component interface. So it contains a reference to the base behavior, and also implements the same interface, hence can be treated as the Component itself. The client code expecting the Component will deal with Decorator without even noticing the difference. In our example CreditCardDecorator.
- ConcreteDecorator: This actually adds responsibility to the component. The class that inherits from Decorator and may add some additional specific functionality in the form Validations. In our example CreditCardValidatorBase and CreditCardValidator, CreditCardValidatorBase is just providing Validation functionality and provides validation rules which can be further extended by sub classes if required.
Attached is the Source Code Sample