In this post under Lombok, I will show with example how to use “@Builder” annotation to implement Builder Pattern in our application.
For our example, we use the below Person pojo class.
Person class
package package26;
public class Person {
private String name;
private String city;
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(name).append(":");
stringBuilder.append(city);
return stringBuilder.toString();
}
}
To implement Builder pattern for our “Person” class we will apply “@Builder” annotation at class level as shown below
Person class with Builder annotation
package package26;
import lombok.Builder;
@Builder
public class Person {
...
}
This annotation will create
1) “PersonBuilder” static nested class
2) “builder” static method in the “Person” class. This method will return instance of “PersonBuilder” class.
3) A non-static method in “PersonBuilder” class for every non-static non-final field in “Person” class.
4) Each of these non-static method in “PersonBuilder” class will return an instance of “PersonBuilder” class. As a result we can chain the methods.
5) The name of each non-static method in “PersonBuilder” class will be equal to non-static non-final field names in “Person” class.
6) Finally A “build” non-static method in “PersonBuilder” clas which will return an instance of “Person” class with data taken by “PersonBuilder” class methods.
Below is the modified class structure
Modified Person class
package package26;
public class Person {
private String name;
private String city;
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(this.name).append(":");
stringBuilder.append(this.city);
return stringBuilder.toString();
}
Person(String name, String city) {
this.name = name;
this.city = city;
}
public static PersonBuilder builder() {
return new PersonBuilder();
}
public static class PersonBuilder {
private String name;
private String city;
PersonBuilder() {
}
public PersonBuilder name(String name) {
this.name = name;
return this;
}
public PersonBuilder city(String city) {
this.city = city;
return this;
}
public Person build() {
return new Person(this.name, this.city);
}
public String toString() {
return "Person.PersonBuilder(name=" + this.name + ", city=" + this.city + ")";
}
}
}
Below is the main class that shows how we use create the “Person” instance using builder pattern.
Main class
package package26;
public class Example26 {
public static void main(String[] args) {
Person person = Person.builder()
.name("Adam Savage")
.city("San Francisco")
.build();
System.out.println(person);
}
}
Below is the output
Output
Adam Savage:San Francisco