Builder Design Pattern In Java
Join the DZone community and get the full member experience.Join For Free
Here I am with my another article on design patterns - Builder Design Pattern. A very useful creational design pattern that lets us construct complex objects step by step.
Builder Design Pattern
- The Builder design pattern is designed to provide a flexible solution to various object creation problems in object-oriented programming.
- The Builder design pattern provides a way to separate the construction of a complex object from its representation.
- The Builder pattern constructs a complex object by using simple objects and step by step approach.
- The pattern provides one of the best ways to create a complex object.
- It is one of the Gang of Four design patterns that describe how to solve recurring design problems in object-oriented software.
- This pattern is useful to build different immutable objects using same object building process.
The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.
So the important components of Builder Design Pattern are as below:
- Product — The Class which defines the complex object we are trying to build step by step using simple objects.
- Builder — The abstract class/interface which defines all the steps required to perform to produce the complex Product object. Generally, each step is declared here (abstract) since the implementation comes under the concrete builder class.
- ConcreteBuilder — The Builder class which provides the actual code to build the Product object. We can have number of different ConcreteBuilder classes each one giving a different flavor or way of producing the Product object.
- Director — The class under which supervision builder performs the ordered steps to build the Product object. The Director normally receives the builder to perform the steps in correct order to build the Product object.
The Builder design pattern solves problems like:
- How can a class (the same construction process) create different representations of a complex object?
- How can a class that includes creating a complex object be simplified?
Let's implements a Car Manufacturing Example using Builder Design Pattern.
Car Manufacturing Example Using Builder Design Pattern
Step 1: Create Car class which is Product in our example:
Please note here that I have added a validation method
doQualityCheck in the class. I believe
Builder should not produce any incomplete or invalid
Product object. So this method will help us in validating the car manufacturing.
Step 2: Create the
CarBuilder abstract class/interface to define all of the required steps to build the Car.
Please notice that I made the return type
CarBuilder as return type of all steps created here. This will help us in steps calling in a chained way. Here, one very important method build which is to get the result or create final object of Car. This method will actually checks the validity of the car and delivers (returns) it only if its manufacturing is complete (valid).
Step 3: Now it's time to write
ConcreteBuilder. As I mentioned that we can have different flavors of
ConcreteBuilder and each one performs its manufacturing in its own way to provide different representations on the Complex
So, here we have code of
ClassicCarBuilder which manufacture old car model.
Now another builder
ModernCarBuilder to build a latest car model.
SportsCarBuilder to build a sports car.
Step 4: Now we will write a Director class call
AutomotiveEngineer under which supervision the builder will build the Car in step by step in correct order.
We can see that the
manufactureCar method is calling the car building steps in correct order.
Now, it's time to write a Main class to execute and test the output.
Below is the output of the program:
I hope we are good with the explanation and example to understand the
Builder Pattern. Few of us also find this matching with Abstract Factory Pattern which I have covered in my another article. The main difference between Builder Pattern and Abstract Factory Pattern is that, Builder provides us more or better control over the object creation process. In short Abstract Factory Pattern deals with "WHAT" and Builder Pattern deals with "HOW".
The Builder Design Pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.
Source Code can be found here: Real-Builder-Design-Pattern-Source-Code
I found builder pattern very useful and one of the most commonly used in the applications nowadays. I found Builder more useful while dealing with the immutable objects. We all know how much good immutable objects and the use of immutable objects is getting increased day by day, especially after release of Java 8.
I use Builder for writing my immutable complex classes and I like to present the idea here.
As an Example, We have an
Employee class in which we have number of fields.
Suppose only 2 fields
EmpName are mandatory, and the rest all are optional. Since it's an immutable class, I have 2 choice while writing constructors.
- Write a constructor with the parameters for all the fields.
- Write multiple constructors for different combination of parameters to create different representations of Employee object.
I thought option 1 is not good since I don't like to have more than 3-4 parameters in a method. That's not look good and it even worst when many of parameters are null or zero.
Option 2 is also not very good since we end up creating too many constructors.
So, here is the solution with the help of Builder Pattern:
EmployeeBuilder as a public static nested class. You can write as normal public class in a separate Java file. There is not much difference in both.
EmployeeMain program to execute and create an
I hope you like the idea. We can use this even in creating more complex objects. I did not wrote Director here, since all steps (collecting values for fields) are not compulsory and can be done in any order. Just to make sure, I am creating an
Employee object only after getting all the mandatory fields, I wrote a validation method.
Restaurant Order Placement Example With Builder Pattern
I am sharing code for a Restaurant Order Placement where Order is immutable object and requires Order Service Type (Take Away/Eat Here), all the Food Items we want, and the Customer Name(optional) at the time of placing the order. Food Items can be as many as we want. So, here is the code for the example.
Meal class. The
Meal class offers predefined food-items with discount on item-price (not on packing-price).
Beverages comes in a size. So, here is the code for
MutiPack packing to support Meal packing where we use different packing for different food items.
Code for utility
BillPrinter class which I wrote to print an itemized bill.
Now, since almost everything is ready. It's time to write our immutable
And now here is the code for
OrderBuilder, which will build the
Done! Now it's time to write a Main program to execute and test the output:
And here's the output of the program:
Well, there you have it! I hope this tutorial helped to understand Builder pattern.
Source Code can be found here: Real-Builder-Design-Pattern-Source-Code
Liked the article? Please don't forget to press that like button. Happy coding!
Need more articles on Design Patterns? Please visit my profile to find more: Brijesh Saxena
Opinions expressed by DZone contributors are their own.