Decorator Design Pattern in Java
Hello!!! Today is Friday so… It’s Friday then Saturday Sunday what? 🚗 🕺 .. Well a new weekend coming and a pattern reviewed, the Decorator let’s see below how this helps us on composition.
Intent
From GOF[1] is “captures class and object relationships that support embellishment by transparent enclosure. The term “embellishment” actually has broader meaning than what we’ve considered here. In the Decorator pattern, embellishment refers to anything that adds responsibilities to an object”.
Well good, adds responsibilities for me means add more behaviour, i.e. methods.
Motivation
The motivation to use this pattern could be to add the behaviour as said before or even be a wrapper class.
In Java EE there is an annotation Decorator and does “The
decorators
example, which is yet another variation on theencoder
example, shows how to use a decorator to implement additional business logic for a bean. Instead of having the user choose between two alternative implementations of an interface at deployment time or runtime, a decorator adds some additional logic to a single implementation of the interface.”
Structure
Example
Below check each class on the class diagram or you prefer click here to go to repository.
Tests
Here is possible to see how to use the Decorator.
Given an electrical engine with some hp (horsepower) a class of type TurboCharger can wrapper this engine and add more responsibilities, in this case, more hp.
For this test is the same, create a new engine and add more hp using a decorator.
Conclusion
This pattern is very useful and if you already working with OutputStream and this kind of class in Java maybe you have created a Decorator.
Source code
References
1 — https://learning.oreilly.com/library/view/design-patterns-elements/0201633612/ch02.html
2 — https://pt.wikipedia.org/wiki/Decorator
3 — https://www.leisurewheels.co.za/blogs/types-of-turbochargers-2/
4 — https://docs.oracle.com/javaee/7/tutorial/cdi-adv-examples005.htm
5 — https://www.zmescience.com/science/types-of-engines/
6 — https://www.motor1.com/news/353404/mercedes-amg-a45-engine-specs/
7 — https://en.wikipedia.org/wiki/Porsche_959
8 — https://learning.oreilly.com/library/view/head-first-design/0596007124/