Builder Design Pattern

Last modified on October 5th, 2014 by Joe.

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.

Complex Object Construction

Complex Object Construction

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]

What is the difference between abstract factory and builder pattern?

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.

Sample builder design pattern implementation in Java API

DocumentBuilderFactory , StringBuffer, StringBuilder are some examples of builder pattern usage in java API.

Sample Java Source Code for Builder Pattern

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);
	}
}

Output of the above sample program for builder pattern

Builder constructed: com.javapapers.sample.designpattern.builder.House@7d772e

Comments on "Builder Design Pattern"

  1. Muhammad Ghazali says:

    Nice example with java for builder pattern dude, thank you :)

  2. Thangarasu Perumal says:

    The way you demonstrated the design pattern is really amazing.
    Thank You dude

  3. Ragu says:

    Your example helped me to Visualize the builder Pattern very easily

    Thanks,
    Ragu

  4. Phil says:

    Thanks for this, I had always wondered what the difference between Abstract Factory pattern and Builder pattern was.

  5. Kit says:

    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();

  6. SMiGL says:

    Excelent post! can u pls explain all design pattern using java

  7. Rahul Batra says:

    @Kit: Yup, +1 for you!

  8. Hiren says:

    Keep up good work, exlpanined very well. pls write on all java design patterns

  9. Devaki says:

    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.

  10. Satya Bulusu says:

    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.

  11. Satya Bulusu says:

    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 :)

  12. manikandan adhimoolam says:

    Thanks for your information.its very useful

  13. amit says:

    Builder design pattern wonderfully explianed with example!!

  14. […] pattern may look similar to builder design pattern. There is a huge difference to it. If you remember, “the same construction process can create […]

  15. Joe says:

    @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.

  16. Nitin says:

    Builder pattern, gives one more additional benefit. You can plugin your implementation into the existing developed framework.

  17. Eman Ahmed Elsayed says:

    Thanks to the author
    As I read this topic from more than site and I get it only from here

  18. Eman Ahmed Elsayed says:

    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

  19. amit says:

    good work dear

  20. Mansoor Ahmed Jamali says:

    Such a nice and amazing example ! Really appreciating. It cleared all my doubts regarding this pattern. Thanks pal ! :)

  21. Anonymous says:

    Excellent article..never expected design pattern can be explained in such a simply way…

  22. Shoaib says:

    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???

  23. anzac says:

    great article – very clear and easy to follow. builder is a great pattern but often misunderstood.

  24. himanshu says:

    Great Example …It will help lot for beginner to understand builder pattern..:)

  25. Mgamerz says:

    You spelled Build wrong in one of the areas, search for ‘bulid’! ;) good example.

  26. Jitendra Gupta says:

    Thanks for the blogs

  27. Rajesh says:

    Nice tutorial

    Rajesh R

  28. Sushant says:

    A real simple explanation of builder pattern. I was always a bit confused as to how the pattern works. Thanks dude. :)

  29. Kunal says:

    What an amazing article!!! almost perfect… If HouseBuilder interface could be renamed to IHouseBuider then it would remove the slight ambiguity.

  30. bill says:

    Amazing article.

  31. Jayaraman says:

    good article

  32. Amit says:

    This is an excellent example. I can visualize the flow. Thanks a lot :-)

  33. Rupesh says:

    Good way to explain a difficult topic

    Thanks
    Rupesh

  34. Jayaprakash says:

    Nice simple example , one suggestion.

    you may remove the AnimalFactory interface in this example , its making confusion.

  35. Amit says:

    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?

  36. Gaurav says:

    @Joe,
    Very Nice!!!!!!

    @Satya
    Great Comment, nice story!!!

  37. Prabhakaran. N says:

    The demo picture is very nice.

  38. Balu says:

    Its Awesome article to understand Builder design Pattern… Many Thanks Joe

  39. chaitanya says:

    awesome explanation but still the difference between abstract factory and builder should have been explained a bit more

  40. Patricia says:

    Nice! i didn’t have it clear… one thing only: it helps (at least to me) if you show an UML of the example :)

  41. Anonymous says:

    Uml diagram would help!

  42. Anonymous says:

    Good One :)

  43. Sudha P says:

    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.

  44. Sudha P says:

    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.

  45. Anand says:

    Excellent way of explaining design patterns with real world examples. Thanks a lot.

  46. v says:

    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.

  47. amjad says:

    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……….

  48. Anonymosu says:

    Good post, Effective Java book also has an Item on this patter, good to read.

  49. amit says:

    really a nice explanation of a difficult concept…

    Thanks dear..

  50. ajax says:

    really nice thanks man

  51. saurabh banerjee says:

    excellent material..include UML

  52. Amit Singh says:

    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.

  53. Samir says:

    Cant see easy way than shis example to explain builder pattern. Thanks!

  54. Cheng says:

    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.

  55. Santosh Gupta says:

    Excellent Example. Could you please provide some real life example?

  56. Selva Kumaran says:

    Good job dude i am the regular reader of your blog . Thanks man for your great work.

  57. Anonymous says:

    Super job keep going

  58. Anonymous says:

    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!

  59. Deepak says:

    Well explained…..

  60. deb says:

    Excellent Understanding….

  61. sampath says:

    well explanation

  62. sayed says:

    its may be the best presentation and exellent example !

  63. Leks says:

    One of the best explanations I have seen

  64. Said Naeem Shah says:

    Very nice easy to visualize it, by giving real world example. Thanks Keep it up :)

  65. Santosh says:

    @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

  66. Abhay says:

    Excellent article …

  67. rim says:

    Good explanation :) thks a lot

  68. Jyothish says:

    Nice tutorial!
    Thanks

  69. Εγω says:

    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

  70. Rico says:

    very nice , thank you so much

  71. Anonymous says:

    Beautiful mode of explanation

  72. yapadekoi says:

    This tutorial would be perfect if there was a plan which explains Builder design pattern and the relation betwain all theses classes.

    Thanks.

  73. Mayank says:

    Thanks for the nice tutorial…

    I thought DocumentBuilderFactory uses Abstract Factory pattern… Not sure if someone can correct me

    Thanks
    Maynak

  74. Anonymous says:

    well explained

  75. arjun says:

    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?

  76. klr psr says:

    Indeed! good article about builder design pattern. Easy to understand. Thanks Joe!

  77. amay says:

    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.

  78. Anonymous says:

    Awe some explanation

  79. Ganesh says:

    Wow Great one.
    Explaination was great.
    Thanks for this.

  80. prashanth says:

    Thanks man!!

  81. Gangeswar says:

    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.

  82. adarsh says:

    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

  83. Anonymous says:

    Well Done!

  84. Venki says:

    Great post

  85. Joe says:

    Thanks Venki.

  86. ram says:

    Thank you very much. Its really help full in understanding of difference between abstract factory and builder.

    Thanks

Comments are closed for "Builder Design Pattern".