Destination
Design Pattern Builder is a design pattern that allows us to separate the object creation from the object’s representation.
When to use?
- If creation algorithm should be independent of object parameters
- If creation algorithm should allow creating many different object’s representations
- The code will be more maintainable if a number of fields required to create an object are more than 4
- The Object is always instantiated in a complete state
- Is useful when you need to do lots of things to build an object
Implementation
/* PersonBuilder */
public class PersonBuilder {
private String firstName;
private String lastName;
private String street;
private Integer age;
public PersonBuiler() {
this.firstName = 'fName';
this.lastName = 'lName';
this.street = 'street';
this.age = 18;
}
public PersonBuilder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public PersonBuilder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public PersonBuilder setStreet(String street) {
this.street = street;
return this;
}
public PersonBuilder setAge(Integer age) {
this.age = age;
return this;
}
public Person build() {
return new Person(this.firstName,
this.lastName,
this.street,
this.age);
}
public Person buildAndSave() {
Person person = this.build();
insert person;
return person;
}
}
/* Person */
public class Person {
private final String firstName;
private final String lastName;
private final String street;
private final Integer age;
public String getName() {
return this.firstName + ' ' + this.lastName;
}
public Person (String firstName,
String lastName,
String street,
Integer age) {
this.firstName = firstName;
this.lastName = lastName;
this.street = street;
this.age = age;
}
}
/* Example of invoke */
public static main() {
Person myPerson = new PersonBuilder()
.setFirstName('Piotr')
.setLastName('Gajek')
.setAge(24)
.build();
}
Diagram

Resources
- “Design Patterns: Elements of Reusable Object-Oriented Software” – Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
- https://en.wikipedia.org/wiki/Builder_pattern
- https://stackoverflow.com/questions/5788240/when-should-i-use-builder-design-pattern/23150589
Was it helpful? Check out our other great articles here.