Design pattern Builder in Java
Disclaimer
This tutorial handle the GOF pattern.
1. Intent
Separate the construction of a complex object from its representation so that the same construction process can create different representations[1].
This motivation help when the class has a lot of attributes and call the constructor with “n” attributes became difficult.
2. Motivation
One of motivations is The Builder pattern captures all these relationships. Each converter class is called a Builder in the pattern, and the reader is called the director[2].
See below how the class are designed.
3. Diagrams
3.1. GOF
In the diagram below the classes/actors are: Director (Constructs an object using the Builder interface[1]), Builder(Specifies an abstract interface for creating parts of a Product object[1]), ConcreteBuilder(Constructs and assembles parts of the product by implementing the Builder interface[1]), Product (Represents the complex object under construction. ConcreteBuilder builds the product’s internal representation and defines the process by which it’s assembled[1] and define the parts assembling the final result, i.e. the product).
3.2. Example
For this example I use an order request for McDonald’s, using my favorite combo of my son the HappyMeal, the sandwich from Vicent Vega and the sauce of Rick’s. In this example the three were classified as combo to make the example easy.
4. Code
4.1. ItemDirector
4.2. Builder
4.3. Item
4.4. HappyMeal
4.5. RoyalCheese
4.6. SzechuanSpecial
4.7. OrderService
4.8. OrderServiceShould
This test class uses JUnit 5, mock injection. The goal of this test is only test the service, thus the concrete builder was mocked.
5. Conclusion
Was my first time using this pattern by the book and isn’t to simple or easy to create by class as I used to do. But at the end of the work it’s worth to learn I think in another approach of Builder pattern.
With the years some patterns has been changed, thus the GOF is a blueprint to take advantage of know problems and has a common language between software engineers.
6. References
[1]https://learning.oreilly.com/library/view/design-patterns-elements/0201633612/ch03.html
[2]https://en.wikipedia.org/wiki/Builder_pattern
7. Code
The complete code is available on my GitHub.