Decorator Design Pattern in Java

Luiz Gustavo De O. Costa
2 min readOct 23, 2020

--

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 the encoder 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

Decorator Design Pattern

Example

Decorator used as example

Below check each class on the class diagram or you prefer click here to go to repository.

Engine
Electrical engine
Four stroke engine
Two stroke engine
TurboCharger Decorator
Decorator for Electrical engine
Decorator for Reaction engine
Decorator for Thermal engine

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

https://github.com/luizgustavocosta/design-patterns-in-java/tree/master/gang-of-four/src/main/java/com/gof/behavioral/decorator

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/

--

--

Luiz Gustavo De O. Costa
Luiz Gustavo De O. Costa

Written by Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices

No responses yet