Decorator

Structural pattern

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.

Decorator design pattern structure.
Decorator design pattern structure.

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.
Decorator pattern sequence diagram.
Decorator pattern sequence diagram.
  1. The Client executes an operation over DecoratorA.
  2. The DecoratorA executes the same operation over DecoradorB.
  3. The decoradorB executes an action over ConcreteComponent.
  4. The DecoradorB executes a decoration operation.
  5. The DecoradorA executes a decoration operation.
  6. The Client receives a decorated object by all the Decorators, which have encapsulated the Component below many layers.

Real-world example

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.

Discover how the Decorator pattern can help us solve this problem.
Discover how the Decorator pattern can help us solve this problem.

About this book

Introduction to design patterns

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
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.