We can use the Builder annotation from Lombok to use the Builder Design Pattern in our Groovy codes. This post shows how to use the Lombok Builder annotation in Groovy. Hence, we need to depend on the Lombok library via Maven or Gradle.
Builder Design Pattern in Java
There are two ways to implement the Builder design pattern in Java. One, we code it ourselves. For instance, consider the following Java codes that implement the Builder Design Pattern. The Person class has a private constructor. It also has an inner class with the name Builder. The Builder inner class is responsible for creating an instance of the Person class. Moreover, the Builder allows us to set the properties of the object it is building indirectly. With Lombok Builder annotation, we do not need to craft such codes in Groovy to implement the Builder design pattern.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public class Person { private final String lastName; private final String firstName; private Person(Builder builder) { this.lastName = builder.lastName; this.firstName = builder.firstName; } public static class Builder { private String lastName; private String firstName; public Builder lastName(String lastName) { this.lastName = lastName; return this; } public Builder firstName(String firstName) { this.firstName = firstName; return this; } public Person build() { return new Person(this); } } public String getLastName() { return lastName; } public String getFirstName() { return firstName; } } |
To use these codes, consider the following example.
1 2 3 4 5 6 | public class Main { public static void main(String... a) { Person p = new Person.Builder().firstName("David").lastName("Lee").build(); } } |
Using Lombok Builder In Groovy
Alternatively, we could use Lombok Builder annotation on a Groovy class to implement the same design pattern. For example, consider the following codes.
1 2 3 4 5 6 7 8 9 10 11 | package com.turreta.groovy import groovy.transform.ToString import groovy.transform.builder.Builder @ToString @Builder class Person { String lastName; String firstName; } |
Although we use Lombok Builder annotation, the builder’s usage is precisely the same. Therefore, we do not need to modify the codes that use our Builder. For example, consider the sample codes below.
1 | Person person = new Person().builder().lastName("Li").firstName("Jet").build(); |
References