Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:See book
The decorator pattern has been designed to solve scenarios where a subclassification hierarchy cannot be applied, or when a great impact is required over all the hierarchy classes in order to achieve the expected behavior. Decorator allows the user to add new features to an existing object without altering its structure through the addition of new classes wrapped around the original one, giving it extra capabilities.
In the above illustration, we can see the all the components involved in the Decorator design pattern, which I'll proceed to explain:
- IComponent: Interface defining the basic structure of the component or components to be decorated.
- ConcreteComponent: IComponent implementation defining a concrete object which can be decorated.
- ComponentDecorator: It usually is an abstract class defining the basic structure of a Decorator, which should inherit from IComponent and contain some IComponent subclass to be decorated.
- ComponentDecoratorImpl: Represents all the concrete decorators which inherit from ComponentDecorator.
- The Client executes an operation over DecoratorA.
- The DecoratorA executes the same operation over DecoradorB.
- The decoradorB executes an action over ConcreteComponent.
- The DecoradorB executes a decoration operation.
- The DecoradorA executes a decoration operation.
- The Client receives a decorated object by all the Decorators, which have encapsulated the Component below many layers.
By implementing the Decorator design pattern, we are going to develop an application for processing a message through layers, where each layer will process it on different levels. First, an object will be converted into XML, then, it's going to be encapsulated into a SOAP message which will then be encrypted. At the end, we're going to get a completely encrypted SOAP message which can be securely sent to a recipient. Each processing layer will be implemented by a decorator, and these decorators can swap positions to provide different results. Also, more decorators can be added between other decorators.