Table of Contents

Related Articles

Builder Design Pattern (is it Simple?)

Share on facebook
Share on twitter
Share on linkedin
Share on email
Share on whatsapp
Share on pinterest
Share on print
Builder Design Pattern

The intention of the Builder Design Pattern is simply saying construct the complex object by using a simple step-by-step process. Representation of the Complex object varies with the construction process.  The builder pattern is doing separates the construction of the complex object. That means in another way same construction process can create different representations.

Let’s make this much easier. When creating the final product there are predefine specific guidelines to follow. That is the construction process. Also, the same object can vary with its representation and there may be many representations of a single product.

This representation change achieves through the construction steps. Builder Design Pattern’s main intention is to separate this construction flow of complex objects from the representation of a single product.

This comes under creational design patterns. This is comparatively a bit difficult to understand, but this is widely used without knowing it’s a pattern. Let’s map this with a real-life example.

When moving into an example, you need to highlight there are main classes participating in Builder Design Pattern.

Participations in Builder Design Pattern

  • Product or Item: This is the thing we are going to build
  • Builder: Production plan or construction flow to follow
  • Product User or Director: Someone or something that executes the Builder

Builder Design Pattern Real World Example

Let’s take a simple example Bank Loan. Clients are looking for loans according to their requirements. Loan type, amount, duration, and rates change according to the client’s needs.  Bank accountants build loans for clients. Let’s move on to the example class diagram first.

Builder Design Pattern
Builder Design Pattern loan Builder

Builder Design Pattern in Java

When going through the code you can realize that loan attributes are private. It’s because of the loan created through the builder. Each builder has its own build method that extends through the abstract Builder(Check OOP Inheritance).

// Main purpose is to create loan
class Loan{
//All the field are private there for no one can create direct loan 
   private double loanAmount;
   private double loanRate;
   private int loanPeriod;
   private int guarantees;
   public Loan(){}
   //loan build through the builder
   public Loan(Builder loanBuilder) {
      this.loanAmount = loanBuilder.loanAmount;
      this.loanRate = loanBuilder.loanRate;
      this.loanPeriod = loanBuilder.loanPeriod;
   }
   public String toString() {
        return "Build a Loan with rate "+this.loanRate+"%, period "
                +this.loanPeriod+" month for "+this.loanAmount+"$ ";
    }

   // Abstract builder 
   abstract class Builder{
      double loanAmount=0;
      double loanRate=0;
      int loanPeriod=0;
      int guarantees;
      public abstract Loan build();
   }

   // First Concrete builder
   class HouseLoanBuilder extends Builder{
      public HouseLoanBuilder(double loanAmount) {
         this.loanAmount = loanAmount;
      }
      public HouseLoanBuilder loanRate(double loanRate) {
         this.loanRate = loanRate;
         return this;
      }

      public HouseLoanBuilder loanPeriod(int loanPeriod) {
         this.loanPeriod = loanPeriod;
         return this;
      }

      public HouseLoanBuilder guarantees(int guarantees) {
         this.guarantees = guarantees;
         return this;
      }
      
      @Override
      public Loan build() {               
         Loan loan=new Loan(this);
         return loan;      
      }
   }

   // Second Concrete builder
   class PersonalLoanBuilder extends Builder{
      public PersonalLoanBuilder(double loanAmount) {
         this.loanAmount = loanAmount;
      }
      public PersonalLoanBuilder loanRate(double loanRate) {
         this.loanRate = loanRate;
         return this;
      }

      public PersonalLoanBuilder loanPeriod(int loanPeriod) {
         this.loanPeriod = loanPeriod;
         return this;
      }
      public PersonalLoanBuilder guarantees(int guarantees) {
         this.guarantees = guarantees;
         return this;
      }
      //Build loan using builder
      @Override
      public Loan build() {               
         Loan loan=new Loan(this);
         return loan;      
      }
   }
}

// Accountant create loans according to the construction flow of builder
// (There are some mandatory and optional information for loans)
public class BankAccountant {
   public static void main(String[] args) {
      // Create personal loan without guarantees
      Loan loan1=new Loan().new HouseLoanBuilder(10000).loanPeriod(60).loanRate(8).build();
      System.err.println(loan1);
      // Create Housing loan with guarantees
      Loan loan2=new Loan().new PersonalLoanBuilder(250000)
                   .loanPeriod(150).loanRate(5).guarantees(2).build();
      System.err.println(loan2);
   }
}

Output

Build a Loan with rate 8.0%, period 60 month for 10000.0$ 
Build a Loan with rate 5.0%, period 150 month for 250000.0$ 

When creating a loan some information is mandatory, but some are optional (Guarantees). So eventually build a loan, but representations are different according to the followed steps to create a loan.

Examples for Builder Design Pattern.

  • java.lang.StringBuilder
  • java.lang.StringBuffer
  • javax.swing package

Example

// StringBuilder builds string
StringBuilder stringBuilder=new StringBuilder("Builder ")
                            .append("Design ").append("Pattern").reverse();
//

Advantages of Builder Design Pattern

  • Objects are created in a complete state with mandatory details.
  • There is no need to create multiple constructors with different parameters.
  • One new attribute is received for the product (Loan) class, then it’s easy to add to an existing one.  No need to add new constructors just need to add them to the builder. That’s not an effect with existing functionality.
  • Immutable objects are created directly.

Summary

Builder Design Pattern is for creating complex objects by a simple step-by-step process. That changes the representation of the complex objects. The pattern makes simple code into a lot of code when the end of the completion, but it helps with maintenance later.

The way of implementing the pattern can vary with the situation, but the intention of the pattern is to create objects in step by step process.

Creating objects by setting all the values through the constructor or setters or creating multiple constructors are not good solutions. That’s easy to create for the first time, but it’s not good in software engineering.

Design Patterns Book

Design Patterns are one of the most famous solutions in programing and millions of people follow them to fix their tasks, design projects, and so on. Most of the patterns create based on basic OOP concepts (If your beginner then read our basic OOP, Encapsulation, Inheritance, Polymorphism, and Abstraction articles with great examples )

There are a lot of articles and design pattern books available with different examples to read. Other than our article if you are interested in this topic you could go through the below books as well.

BooksDescription

Head First Design Patterns: A Brain-Friendly Guide
My favorite and it’s more readable. There are good examples and they look good to beginners as well.

Design Patterns: Elements of Reusable Object-Oriented Software
There are 23 design patterns. showing how to select an appropriate pattern for your case.

Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software
There are a lot of simple examples showing how to use design patterns in the correct way. Those are based on SOLIC principles.
Design Patterns ebook online

There are a lot of design pattern ebooks on Amazon. Those design patterns are written with great examples in a different programming language. I included a few of them according to their best ranking.

Share on facebook
Share on twitter
Share on linkedin
Share on email
Share on whatsapp
Share on pinterest
Share on print

Leave a Comment

Your email address will not be published. Required fields are marked *

Related Posts

You May Like
Subscribe to our Newsletter