Builder Pattern in Java

By | July 4, 2020

In this post, We will talk and learn about the Builder Pattern in Java.

There are mainly three major problems with Factory and Abstract Factory design patterns when the Object contains a lot of attributes.

  1. We have to pass too many arguments from the client program to the Factory class that can be error-prone because most of the time, the type(Data Type) of arguments is the same and from client-side it’s hard to maintain the order of the arguments.
  2. Few of the parameters might be optional but in the Factory pattern, we are forced to send all the parameters and optional parameters need to send as NULL or default value.
  3. If the object is very heavy and Object creation is complex, then all that complexity will be part of Factory classes that is confusing

Builder Design Pattern Example in JDK:

  • java.lang.StringBuilder append() method
  • java.lang.StringBuffer append() method
  • All implementations of java.lang.Appendable(BufferedWriter,
    CharArrayWriter, FileWriter, FilterWriter, OutputStreamWriter PipedWriter, PrintStream,
    PrintWriter, StringWriter, Writer) are in fact good examples of the use of a Builder pattern in java.
  • java.nio.ByteBuffer#put() (also on CharBuffer, ShortBuffer, IntBuffer, LongBuffer, FloatBuffer, and DoubleBuffer)

Below is the complete source code:

Code easily can be understood by reading provided java documentation


Finally, We have a client program 

Output of this Client Program:

Laptop Config::Laptop [ram=16 GB, hdd=240 GB, cpu=2.56 HZ, isGraphicsEnable=false, isBluetoothEnable=false]
Laptop Config::Laptop [ram=32 GB, hdd=1024 GB, cpu=2.56 HZ, isGraphicsEnable=false, isBluetoothEnable=true]
Laptop Config::Laptop [ram=32 GB, hdd=240 GB, cpu=2.56 HZ, isGraphicsEnable=false, isBluetoothEnable=true]


You May Also Like:

Singleton Design Pattern in java
Prototype Pattern in Java
Factory Pattern in Java
Abstract Factory Pattern in Java

That’s all about the Builder Pattern in Java.
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

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