Builder Design Pattern

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.

Ads by Google

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

This Creational Design Pattern tutorial was added on 17/11/2009.

previous post: javapapers.com Celebrates 400000 Pageviews

next post: Java Serialization

89 comments on “Builder Design Pattern

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

  2. Your example helped me to Visualize the builder Pattern very easily

    Thanks,
    Ragu

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

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

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

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

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

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

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

  10. Thanks for your information.its very useful

  11. Builder design pattern wonderfully explianed with example!!

  12. Pingback: Prototype Pattern

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

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

    For more details, refer the blog
    http://xeon2k.wordpress.com

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

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

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

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

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

  20. Pingback: Java Pins

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

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

  23. الله يبض و جهك

    مع اني متاكد انك ما تدري وش سالفة
    thank you

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

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

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

  27. Good way to explain a difficult topic

    Thanks
    Rupesh

  28. Nice simple example , one suggestion.

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

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

  30. @Joe,
    Very Nice!!!!!!

    @Satya
    Great Comment, nice story!!!

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

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

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

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

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

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

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

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

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

  40. really a nice explanation of a difficult concept…

    Thanks dear..

  41. excellent material..include UML

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

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

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

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

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

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

  47. 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!

  48. its may be the best presentation and exellent example !

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

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

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

    Thanks.

  52. Thanks for the nice tutorial…

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

    Thanks
    Maynak

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

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

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

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

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

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

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

    Thanks

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>