Builder pattern is used to construct a complex object step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.
For example, you can consider construction of a home. Home is the final end product (object) that is to be returned as the output of the construction process. It will have many steps, like basement construction, wall construction and so on roof construction. Finally the whole home object is returned. Here using the same process you can build houses with different properties.
GOF says,
“Separate the construction of a complex object from its representation so that the same construction process can create different representations” [GoF 94]
Abstract factory may also be used to construct a complex object, then what is the difference with builder pattern? In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step. But in abstract factory how complex the built object might be, it will not have step by step object construction.
DocumentBuilderFactory , StringBuffer, StringBuilder are some examples of builder pattern usage in java API.
Following is the interface, that will be returned as the product from the builder.
package com.javapapers.sample.designpattern.builder; public interface HousePlan { public void setBasement(String basement); public void setStructure(String structure); public void setRoof(String roof); public void setInterior(String interior); }
Following is the interface for which the factory implementation should be done. Inturn all abstract factory will return this type.
package com.javapapers.sample.designpattern.abstractfactory; public interface AnimalFactory { public Animal createAnimal(); }
Concrete class for the above interface. The builder constructs an implementation for the following class.
package com.javapapers.sample.designpattern.builder; public class House implements HousePlan { private String basement; private String structure; private String roof; private String interior; public void setBasement(String basement) { this.basement = basement; } public void setStructure(String structure) { this.structure = structure; } public void setRoof(String roof) { this.roof = roof; } public void setInterior(String interior) { this.interior = interior; } }
Builder interface. We will have multiple different implementation of this interface in order to facilitate, the same construction process to create different representations.
package com.javapapers.sample.designpattern.builder; public interface HouseBuilder { public void buildBasement(); public void buildStructure(); public void bulidRoof(); public void buildInterior(); public House getHouse(); }
First implementation of a builder.
package com.javapapers.sample.designpattern.builder; public class IglooHouseBuilder implements HouseBuilder { private House house; public IglooHouseBuilder() { this.house = new House(); } public void buildBasement() { house.setBasement("Ice Bars"); } public void buildStructure() { house.setStructure("Ice Blocks"); } public void buildInterior() { house.setInterior("Ice Carvings"); } public void bulidRoof() { house.setRoof("Ice Dome"); } public House getHouse() { return this.house; } }
Second implementation of a builder. Tipi is a type of eskimo house.
package com.javapapers.sample.designpattern.builder; public class TipiHouseBuilder implements HouseBuilder { private House house; public TipiHouseBuilder() { this.house = new House(); } public void buildBasement() { house.setBasement("Wooden Poles"); } public void buildStructure() { house.setStructure("Wood and Ice"); } public void buildInterior() { house.setInterior("Fire Wood"); } public void bulidRoof() { house.setRoof("Wood, caribou and seal skins"); } public House getHouse() { return this.house; } }
Following class constructs the house and most importantly, this maintains the building sequence of object.
package com.javapapers.sample.designpattern.builder; public class CivilEngineer { private HouseBuilder houseBuilder; public CivilEngineer(HouseBuilder houseBuilder){ this.houseBuilder = houseBuilder; } public House getHouse() { return this.houseBuilder.getHouse(); } public void constructHouse() { this.houseBuilder.buildBasement(); this.houseBuilder.buildStructure(); this.houseBuilder.bulidRoof(); this.houseBuilder.buildInterior(); } }
Testing the sample builder design pattern.
package com.javapapers.sample.designpattern.builder; public class BuilderSample { public static void main(String[] args) { HouseBuilder iglooBuilder = new IglooHouseBuilder(); CivilEngineer engineer = new CivilEngineer(iglooBuilder); engineer.constructHouse(); House house = engineer.getHouse(); System.out.println("Builder constructed: "+house); } }
Builder constructed: com.javapapers.sample.designpattern.builder.House@7d772e
Comments are closed for "Builder Design Pattern".
Nice example with java for builder pattern dude, thank you :)
The way you demonstrated the design pattern is really amazing.
Thank You dude
Your example helped me to Visualize the builder Pattern very easily
Thanks,
Ragu
Thanks for this, I had always wondered what the difference between Abstract Factory pattern and Builder pattern was.
Good post on this design pattern. Note that returning ‘this’ from each setXXX() method on the builder allows for the user to string the building process together in a very fluent IDE-friendly style. Eg:
House h = new HouseBuilder()
.setRoof()
.setWalls()
.setFloor()
.build();
Excelent post! can u pls explain all design pattern using java
@Kit: Yup, +1 for you!
Keep up good work, exlpanined very well. pls write on all java design patterns
Until now I thought design patterns are complicated to learn but you made it simple and easy to understand. Now I can easily relate what pattern I am using in my project. Very nice work. Looking for more posts in struts and hibernate.
Thanks and appreciate it.
Devaki.
To be honest with you I think you missed the main concept of Builder pattern i.e. “Same construction process can create different representations”
Think of builder pattern as a “Save As operation that converts a word document to several different formats in a MS Word”.
A word document can be saved as html file or xml file or a pdf file or plain text etc.
So this how Builder pattern works:
1. You have a reader object that reads tokens from a word document. In the Ms Word example the reader a MS Word Document reader class that read each component from the work document say BOLD_STARTED, UNDERLINE_STARTED, WORDS_STARTED etc.
2. Create a Builder interface of methods that respond to various tokens from word documents
2. Now say you a Plain TXT File builder from WORD document tokens. Implement the Builder interface. This builder doesn’t need to respond to all the tokens that are handles by Word document. i.e. this Plain TXT Builder Implementation guy provide NULL (no) implementation for BOLD_STARTED,UNDERLINE_STARTED etc. But he (Plain TXT File Builder Implementation ) needs to implement WORDS_STARTED because in a plain text file all we have is plain words. No Bold or underline.
3. Pass the “Plain TXT File Builder Implementation” and a Builder interface to Reader object
4. Call appropriated methods in a switch-case statements for each token.
The concept behind the builder design pattern is now you can pass a PDF Builder Implementation object as Builder interface object to your MS WORD reader object. It doesn’t know who is building what. So religiously calls each method. The builder guy knows what do.
Here is a story I read when I was a kid:
A business man gave same amount of money to three of his sons and asks them to fill a very closed room completely with any any thing they like by purchasing using the money.
First son buys lot of stray and fills it but only half filled and ran out of money
Second one buys water and filled with it. But slowly water getting seeped out some how.
Third son buys a small lamp and keeps it at the center of the room and light fills the room completely.
Hear Reader is the business man.
His sons are builders. Business man gives the same amount of money to all three of his sons. How they used that money is their wit. Hope I explained well :)
Thanks for your information.its very useful
Builder design pattern wonderfully explianed with example!!
[…] pattern may look similar to builder design pattern. There is a huge difference to it. If you remember, “the same construction process can create […]
@Satya Bulusu – cool. that was an excellent comment. I didn’t miss the core “Same construction process can create different representations”. If you see in the definition, I highlighted it.
I try to keep my posts as simple as possible. I wish my writing to be a starting point. In order to maintain simplicity I have to sacrifice details sometimes.
Builder pattern, gives one more additional benefit. You can plugin your implementation into the existing developed framework.
Thanks to the author
As I read this topic from more than site and I get it only from here
thanks a lot,I’m studding now design pattern in my faculty and I can’t understood it.
but when I read your papers Joe, I understood and become very happy.
Please, Can you explain structural, behavioral and partitioning design pattern in java?
please reply to me I really need a help in design pattern
Greetings from Egypt
Thanks,
Eman
good work dear
Such a nice and amazing example ! Really appreciating. It cleared all my doubts regarding this pattern. Thanks pal ! :)
Excellent article..never expected design pattern can be explained in such a simply way…
good work dude!!!
can u send me uml class diagram of this code??? plz
my email is shoaibmanzoor786@hotmail.com
or tell where it is located in this site???
great article – very clear and easy to follow. builder is a great pattern but often misunderstood.
Great Example …It will help lot for beginner to understand builder pattern..:)
You spelled Build wrong in one of the areas, search for ‘bulid’! ;) good example.
Thanks for the blogs
Nice tutorial
Rajesh R
A real simple explanation of builder pattern. I was always a bit confused as to how the pattern works. Thanks dude. :)
What an amazing article!!! almost perfect… If HouseBuilder interface could be renamed to IHouseBuider then it would remove the slight ambiguity.
Amazing article.
good article
This is an excellent example. I can visualize the flow. Thanks a lot :-)
Good way to explain a difficult topic
Thanks
Rupesh
Nice simple example , one suggestion.
you may remove the AnimalFactory interface in this example , its making confusion.
I was executing this code and i think something is wrong somewhere.
I don’t see anywhere value of the house attributes being set.
Can you please confirm?
@Joe,
Very Nice!!!!!!
@Satya
Great Comment, nice story!!!
The demo picture is very nice.
Its Awesome article to understand Builder design Pattern… Many Thanks Joe
awesome explanation but still the difference between abstract factory and builder should have been explained a bit more
Nice! i didn’t have it clear… one thing only: it helps (at least to me) if you show an UML of the example :)
Uml diagram would help!
Good One :)
Very Good Example.Thanks a lot. In a interview that I have attended recently asked the pictorial explanation for design patterns. I couldn’t find those explanation in anywhere. It helps, If you show the diagram.
Very Good Example.Thanks a lot. In a interview that I have attended recently asked the pictorial explanation for design patterns. I couldn’t find those explanation in anywhere. It helps, If you show the diagram.
Excellent way of explaining design patterns with real world examples. Thanks a lot.
The Builder pattern suggests moving the construction logic out of the object class to a separate class referred to as a builder class. There can be more than one such builder class each with different implementation for the series of steps to construct the object. Each such builder implementation results in a different representation of the object. This type of separation reduces the object size.
Thanks for your nice explanation, first time i know about java design pattern from your blog. This is so good example. Go ahead, and share knowledge. Good luck……….
Good post, Effective Java book also has an Item on this patter, good to read.
really a nice explanation of a difficult concept…
Thanks dear..
really nice thanks man
excellent material..include UML
Just a suggestion.
It will be good if you add below code
public String toString()
{
return this.basement+”…”+this.structure+”….”+this.roof+”…”+this.interior;
}
in house class .
And in BuildSample Class add
System.out.println(“Builder constructed: “+house.toString());
It will help in knowing which house is actually getting created.
Cant see easy way than shis example to explain builder pattern. Thanks!
I don’t quite understand why getHouse() and constructHouse() need to be separated. Can’t we merge the 2 functions by putting the constructHouse code into the getHouse()?
Can someone please explain? Thanks.
Excellent Example. Could you please provide some real life example?
Good job dude i am the regular reader of your blog . Thanks man for your great work.
Super job keep going
I do not think the example is good cause it makes me more confused. What is the intent of CivilEngineer? In your example, I do not think it is necessary. Change the constructor to { this.house = new House(); this.buildBasement(); .. this.buildInterior();} will solve the problem!
Well explained…..
Excellent Understanding….
well explanation
its may be the best presentation and exellent example !
One of the best explanations I have seen
Very nice easy to visualize it, by giving real world example. Thanks Keep it up :)
@Cheng:
Well asked about getHouse(); and constructHouse();
If you could Imagine a much complex code going into the construction details (business logic), you will appreciate the presentation of the house to be separated out from it’s configuration.
@Joe: Kudos for such an exemplary treatment to design patterns, much appreciated.
But what it felt to me when you wish to give details on the getHouse(). This could be much better expained if we have overriden the Object.equals() method to give every details on what the house comprise of.
Cheers,
Santosh
Excellent article …
Good explanation :) thks a lot
Nice tutorial!
Thanks
Finally! I nice and clear example about builder! I was strangling on google to find a simple example! what i hell.. Why they mix up builders with factories and flyweights along with java libraries..
IT IS SO SIMPLE! WAY TO GO TO THE INSTRUCTOR
very nice , thank you so much
Beautiful mode of explanation
This tutorial would be perfect if there was a plan which explains Builder design pattern and the relation betwain all theses classes.
Thanks.
Thanks for the nice tutorial…
I thought DocumentBuilderFactory uses Abstract Factory pattern… Not sure if someone can correct me
Thanks
Maynak
well explained
Same can be done with templete pattern. tell me waht is diff between templete method and builder. But dont say builder creation patten and templete is behavior pattern. Please explain me with some eample which one has to be used when?
Indeed! good article about builder design pattern. Easy to understand. Thanks Joe!
Thanks alot ..Your articles are amazing.
I have question : why dont we return house in constructHouse() of civil engineer.
Instead of client asking for house by separate method.
Awe some explanation
Wow Great one.
Explaination was great.
Thanks for this.
Thanks man!!
Hi Joe,
In the above “Sample Java Source Code for Builder Pattern”
What is the use of “AnimalFactory” interface?
I think its the code related to “Factory Method” in your prevoius example, please correct me If I am wrong.
Hi Joe,
Isn’t it a better way to have static nested builder object created than using JavaBeans for Builder pattern.(Picked the concept from Effective Java )
Please pen down your thoughts.
Thanks,
Adarsh
Well Done!
Great post
Thanks Venki.
Thank you very much. Its really help full in understanding of difference between abstract factory and builder.
Thanks