Provide a way to create a complex object with different representation in a simplified manner
This design pattern helps to get rid of the "telescopic constructor"
Check code here
public class Item {
private String name;
private String description;
public Item(String name, String description) {
this.name = name;
this.description = description;
}
}
public class ItemBuilder {
private String name;
private String description;
public ItemBuilder name(String name) {
this.name = name;
return this;
}
public ItemBuilder description(String description) {
this.description = description;
return this;
}
public Item build() {
return new Item(name, description);
}
}
To access the instance
Item item = new ItemBuilder()
.name("item name")
.description("item description")
.build();
You can apply the builder design pattern by simply adding the lombok @Builder
annotation on the class
@Builder
public class Item {
private String name;
private String description;
}
To access the instance
Item item = Item.builder()
.name("item name")
.description("item description")
.build();
StringBuilder
with the methodappend(String str)
to concatenate strings