Design Patterns #1 – Builder


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


/* 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, 

   public Person buildAndSave() {
      Person person =;
      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()


diagram of builder pattern in apex
Diagram of Builder


Was it helpful? Check out our other great articles here.

4.6 7 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Close Menu
Would love your thoughts, please comment.x