Saturday, 29 September 2012

Builder design pattern in java

Builder design pattern allows to create complex object step by step and also enforces a process to create an object as a finished product.Construction of object should be such that same construction process can create different representations.Director controls the construction of object and only director knows what type of object to create.

For example, You can consider printing of a book.Printing of a book involves various steps such as printing table of content,preface,introduction,chapters and conclusion.Finally you will get complete book object. With the help of same above process,you can print books with different properties.
 
As described by Gof:
"Separate the construction of a complex object from its representation so that the same construction process can create different representations"

Generic UML diagram for builder design pattern:

Elements:

  • Builder
    • specifies an abstract interface for creating parts of a product object.
  • ConcreteBuilder
    • constructs and assembles parts of the product by implementing the builder interface.
    • defines and keeps track of the representation it creates.
    • provides an interface for retrieving the product.
  • Director
    • constructs an object using builder interface.
  • Product
    • represents the complex object under construction.ConcreteBuilder builds the product's internal representation and defines the process by which it is assembled.
    • includes classes that define the constituent parts,including interfaces for the assembling the parts into final result.

When to use it:

  • Object creation algorithms should be independent of system.
  • New creation algorithm can be added without changing core code.
  • The construction process must allow different representations for the object that' s contructed.
  • Runtime control over creation process is required.

WorkFlow:

  • The client creates the director object and configures it with the desired builder object.
  • Director notifies builder whenever a part of product should be built.
  • Builder handles requests from the director and adds parts to the product.
  • The clients retrieves the product from builder.

Example:

You can consider priniting of a book.Printing of a book involves various steps such as printing table of content,preface,introduction,chapters and conclusion.Finally you will get complete book object. With the help of same above process,you can write books with different properties.  BookWriter will instruct bookBuilder to print book in steps and return final book object.

Comparing to generic UML diagram of builder pattern:
  • BookBuilder(Builder)
  • TechnicalBookBuilder(ConcreteBuilder)
  • FictionalBookBuilder(ConcreteBuilder)
  • BookWriter(Director)
  • Book(Product)
Java codes for above classes:
Following class is our product class.Object of this class will be returned by builder.

Book.java (Product):
package org.arpit.javapostsforlearning.designpatterns;

public class Book {

 String introduction;
 String tableOfContent;
 String preface;
 String chapters;
 String glossary;
  
 public void setIntroduction(String introduction) {
  this.introduction = introduction;
 }
 public void setTableOfContent(String tableOfContent) {
  this.tableOfContent = tableOfContent;
 }
 public void setPreface(String preface) {
  this.preface = preface;
 }
 public void setChapters(String chapters) {
  this.chapters = chapters;
 }
 public void setGlossary(String glossary) {
  this.glossary = glossary;
 }
}
Following interface is our builder interface.Builder interface provides steps or process.Here we have five steps-buidTableOfContent,buildPreface,buildIntroduction,buildChapters,buildGlossary.It also has method to return book(product) object. 
BookBuilder.java (Builder):
package org.arpit.javapostsforlearning.designpatterns;

public interface BookBuilder {

        public void buildTableOfContent();
        public void buildPreface();
        public void buildIntroduction();
        public void buildChapters();
        public void buildGlossary();
        public Book getBook();
}
Following class is our first implementation of builder interface.We are having multiple concrete builder class to support  same construction process creating multiple representations.

TechnicalBookBuilder.java(ConcreteBuilder):
package org.arpit.javapostsforlearning.designpatterns;

public class TechnicalBookBuilder implements BookBuilder{
 private Book book;

 public TechnicalBookBuilder()
 {
  book=new Book();
 }
 public void buildTableOfContent() {
  System.out.println("printing technical table of content");
  book.setTableOfContent("technical table of content");
 }
 
 public void buildPreface() {
  System.out.println("printing preface");
  book.setTableOfContent("preface");
 }
 public void buildIntroduction() {
  System.out.println("printing technical introduction");
  book.setTableOfContent("technical introduction");
 }

 public void buildChapters() {
  System.out.println("printing technical chapters");
  book.setChapters("technical chapters");
 }

 public void buildGlossary() {
  System.out.println("printing technical glossary");
  book.setGlossary("Technical glossary");
 }

 public Book getBook() {
  return book;
 }
}

Following class is our second implementation of builder interface.

FictionalBookBuilder.java(ConcreteBuilder):
package org.arpit.javapostsforlearning.designpatterns;

public class FictionalBookBuilder implements BookBuilder{
 private Book book;

 public FictionalBookBuilder()
 {
  book=new Book();
 }
 public void buildTableOfContent() {
  System.out.println("printing fictional table of content");
  book.setTableOfContent("fictional table of content");
 }
 
 public void buildPreface(){
  System.out.println("printing preface");
  book.setTableOfContent("preface");
 }
 public void buildIntroduction() {
  System.out.println("printing fictional introduction");
  book.setTableOfContent("fictional introduction");
 }

 public void buildChapters() {
  System.out.println("printing fictional chapters");
  book.setChapters("fictional chapters");
 }

 public void buildGlossary() {
  System.out.println("printing fictional glossary");
  book.setGlossary("Fictional glossary");
 }

 public Book getBook() {
  return book;
 }

}

Following class is our director class which will instructs BookBuilder to print parts of book and return final book object
BookWriter.java(Director):
package org.arpit.javapostsforlearning.designpatterns;
public class BookWriter {

 BookBuilder bookBuilder;
 
 public BookWriter(BookBuilder bookBuilder) {
  super();
  this.bookBuilder = bookBuilder;
 }

 public Book getBook()
 {
  return this.bookBuilder.getBook();
 }
 
 public void printBook()
 {
  this.bookBuilder.buildTableOfContent();
  this.bookBuilder.buildPreface();
  this.bookBuilder.buildIntroduction();
  this.bookBuilder.buildChapters();
  this.bookBuilder.buildGlossary();
 }
}
BuilderDesignPatternMain.java:
package org.arpit.javapostsforlearning.designpatterns;
public class BuilderDesignPatternMain {
 
 
 public static void main(String[] args) {
  
  System.out.println(Printing technical book:");
  BookBuilder technialbookBuilder=new TechnicalBookBuilder();
  BookWriter technicalBookWriter=new BookWriter(technialbookBuilder);
  technicalBookWriter.printBook();
  Book technicalbook=technicalBookWriter.getBook();
  System.out.println("Technical Book Printed:"+technicalbook);
  System.out.println("******************************************");
  System.out.println(Printing fictional book:");
  BookBuilder fictionalbookBuilder=new FictionalBookBuilder();
  BookWriter fictionalBookWriter=new BookWriter(fictionalbookBuilder);
  fictionalBookWriter.printBook();
  Book fictionalbook=fictionalBookWriter.getBook();
  System.out.println("Fictionalbook book printed:"+fictionalbook);
 }
} 
For printing technical book,we have configured bookWriter object with technicalBookBuilder.BookWriter instructed to technicalbookbuilder to print book and return final book object.Same is true for fictional book.So with help of same construction process,we have printed two kinds of book.i.e. technical and fictional.
Output:
Printing technical book:
printing technical table of content
printing preface
printing technical introduction
printing technical chapters
printing technical glossary
Technical Book printed:org.arpit.javapostsforlearning.designpatterns.Book@1888759
******************************************
Printing fictional book:
printing fictional table of content
printing preface
printing fictional introduction
printing fictional chapters
printing fictional glossary
Fictionalbook book printed:org.arpit.javapostsforlearning.designpatterns.Book@1f1fba0 

References:The Gang of Four (GoF) book
 

Java tutorial for beginners Copyright © 2011 - |- Template created by O Pregador - |- Powered by Blogger Templates