Design Patterns #1 – Builder

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

diagram of builder pattern in apex
Diagram of Builder

Resources

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

4.4 5 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Close Menu
0
Would love your thoughts, please comment.x
()
x