I decided that I wanted to talk a little more for the design patterns. This week I will present you another type. Decorator Design Pattern. Decorator design pattern is used to add additional features or behaviors to a particular instance of a class, while not modifying the other instances of same class. It is a structural pattern, which provides a wrapper to the existing class. The reason why this pattern is in structural design patterns is because they show us how to glue different pieces of a system together in a flexible and extensible fashion. These patterns help us guarantee that when one of the parts changes, the entire application structure does not need to change.
What is the intent of this pattern? In software engineering, decorator design pattern is used to add additional features or behaviors to a particular instance of a class, while not modifying the other instances of same class. The intent of the this pattern is to provide a flexible alternative to sub-classing for extending functionality. This pattern is very important to understand because once you know the techniques of decorating, you’ll be able to give your (or someone else’s) objects new responsibilities without making any code changes to the underlying classes. You can attach new responsibility to an object dynamically. This is exactly the intended use of the decorator pattern. Per the Gang of Four – “Attach additional responsibilities to an object dynamically”.
When to use this pattern? Decorator Design Pattern has several requirement indicators to suggest that it is potential solution e.g.
- We have an object that requires the extension.
- Several objects that support the extension by “decoration”. Usually, those objects share a common interface, traits, or superclass, and sometimes, additional, intermediate super-classes .
- The decorated object (class or prototype instantiation), and the decorator objects have one or several common features. In order to ensure that functionality, the decorated object & the decorators have a common interface, traits, or class inheritance.
What are the benefit and disadvantages?
· Sometimes we want to add responsibilities to individual objects, not to an entire class. Decorators provide a flexible alternative to subclassing for extending functionality.
· Avoids feature-laden classes high up in the hierarchy.
· A decorator and its component aren’t identical.
· Lots of little objects.
There are a lot of examples and reading that you can do for this design. I would suggest you https://howtodoinjava.com/design-patterns/structural/decorator-design-pattern/ . This is a very good website where it gives details what the Decorator Pattern is and it gives you an example to understand it better. Also https://dzone.com/articles/decorator-design-pattern-in-java . What I like about this website is that it has all the important part in points. Touch only the important part without going to much in details for a beginner.