Skip to main content

Design Pattern : Builder Design Pattern


Design Pattern : Builder Design Pattern


Builder design pattern in Java is a creational pattern i.e. used to create objects, similar to factory method design pattern which is also creational design pattern.

What problem Builder pattern solves in Java

Builder pattern is a creational design pattern it means its solves problem related to object creation. Constructors in Java are used to create object and can take parameters required to create object. Problem starts when an Object can be created with lot of parameters, some of them may be mandatory and others may be optional.

 

Guidelines for Builder design pattern in Java 

1) Make a static nested class called Builder inside the class whose object will be build by Builder. In this example its Alert Dialog.

2) Builder class will have exactly same set of fields as original class.

3) Builder class will expose method for adding properties for alert dialog e.g. title, message in this example. each method will return same Builder object. Builder will be enriched with each method call.

4) Builder.build() method will copy all builder field values into actual class and return object of Item class.

5) Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor.

Example:

 I have implemented AlertDialog concept using Builder pattern.


public class AlertDialog {
  
   // All final Attributes
   private final String title;  // Optional
   private final String subTitle; // Optional
   private final String message; // Optional
   private final String firstButtonText; // Optional
   private final String secondButtonText; // Optional
  
   private AlertDialog(Builder builder) {
  
         this.title = builder.title;
         this.subTitle = builder.subTitle;
         this.message = builder.message;
         this.firstButtonText = builder.firstButtonText;
         this.secondButtonText = builder.secondButtonText;
   }
  
   public String getTitle() {
      return title;
   }
   public String getSubTitle() {
      return subTitle;
   }
   public String getMessage() {
      return message;
   }
   public String getFirstButtonText() {
      return firstButtonText;
   }
   public String getSecondButtonText() {
      return secondButtonText;
   }


   public static class Builder {
     
      // All final Attributes
      private String title = "";  // Optional
      private String subTitle = ""; // Optional
      private String message = ""; // Optional
      private String firstButtonText = ""; // Optional
      private String secondButtonText = ""; // Optional
  
      public Builder setTitle(String title) {
         this.title = title;
         return this;
      }

      public Builder setSubTitle(String subtitle) {
         this.subTitle = subtitle;
         return this;
      }

      public Builder setMessage(String message) {
         this.message = message;
         return this;
      }

      public Builder setFirstButtonText(String text) {
         this.firstButtonText = text;
         return this;
      }

      public Builder setSecondButtonText(String text) {
         this.secondButtonText = text;
         return this;
      }
     
      public AlertDialog Build() {
         AlertDialog dialog = new AlertDialog(this);
         validateInputs(dialog);
         return dialog;
      }
     
      public void validateInputs(AlertDialog dlg) {
         // Do validation heres
      }
   }

   public void show() {

      if(title != null && title != "")
         System.out.println("Title : " + title);
      if(subTitle != null && subTitle != "")
         System.out.println("Sub Title : " + subTitle);
      if(message!= null && message!= "")
         System.out.println("Message : " + message);
      if(firstButtonText!= null && firstButtonText!= "")
         System.out.println("First Button : " + firstButtonText);
      if(secondButtonText!= null && secondButtonText!= "")
         System.out.println("Second Button : " + secondButtonText);
     
   } 
}

Below is the code for creating object with builder pattern.

public class MainClass {
  
    public static void main(String[] args) {

       AlertDialog dialog = new AlertDialog.Builder()
                   .setTitle("Hello")
                   .setSubTitle("Prashant Bale")
                   .setMessage("How are you?")
                   .setFirstButtonText("Fine")
                   .setSecondButtonText("Not Good")
                   .Build();
      
       dialog.show();

       AlertDialog dialog2 = new AlertDialog.Builder()
            .setTitle("Hello")
            .setSubTitle("Prashant Bale")
            .Build();

       dialog2.show();
   
    }
}




Builder design pattern in Java – Pros and Cons
Live everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.



Advantages:

1) more maintainable if number of fields required to create object is more than 4 or 5.

2) less error-prone as user will know what they are passing because of explicit method call.

3) more robust as only fully constructed object will be available to client.



Disadvantages:

1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.



Reference link:
http://javarevisited.blogspot.in/2012/06/builder-design-pattern-in-java-example.html



Comments

Popular posts from this blog

Protect sensitive information or credentials using Android Keystore

The Android keystore provides secure system level credential storage. With the keystore, an application creates a new Private/Public key pair, and uses this to encrypt application secrets before saving it in the private storage. We will learn how to use Android keystore to create and delete keys also how to encrypt the user sensitive data using these keys. The Keystore system is used by the  KeyChain API as well as the Android Keystore provider feature that was introduced in Android 4.3 (API level 18). This document goes over when and how to use the Android Keystore provider Android has had a system-level credential storage since Donut (1.6). Up until ICS (4.0), it was only used by the VPN and WiFi connection services to store private keys and certificates, and a public API was not available. ICS  introduced  a public  API   and integrated the credential storage with the rest of the OS.  Why to use Keystore?     ...

How to access a Android database by using a command line.

How to access a Android database by using a command line. Many of us uses databases in android applications, So it is very important to know how it is store, where it is store in the device and how to access that database directly outside from your program. That is helpful to understand whether our database code working as per expectation. Steps to do that: 1) You need to launch the emulator first. Better launch your database application from Eclipse.  ( Note: Even you can connect your real device to your PC for this. ) 2) Launch a command prompt in the android platform-tools directory. ( Directory which has adb.exe ) 3) type  adb shell . This will launch an unix shell on your emulator / connected device. 4) go to the directory where your database is : ( beware, Unix is case sensitive !! ) cd data/data here you have the list of all the applications on your device Go in your application directory  cd com.employeedirectory and descend in your databases directo...

AWS Mobile Services

AWS Mobile Services  There are few AWS services listed below which can be used in mobile applications so that applications are sophisticated cloud-powered.  1. Amazon Cognito ( Identity )      simplifies the task of authenticating users and storing, managing, and syncing their data across multiple devices, platforms, and applications. It works online or offline, and allows you to securely save user-specific data such as application preferences and game state. Cognito works with multiple existing identity providers and also supports unauthenticated guest users . 2. Lambda      AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume - there is no charge when your code is not running. With Lambda, you can run code for virtually any type of application or backend service - all with zero administration. Just upload your code and Lambda takes care of everything required to...