Builder Pattern

Builder pattern belongs to Creational Patterns. This is nothing new. What i have done is just accumulated the information with an C# example.

When to use?

  • Is your object's construction process is too complex?
  • Is your object's representation is different with the same construction process?

Purpose

Separate the construction process from it's representation so that same construction process can create different representation.

Class diagram

                               
 

The classes and/or objects participating in this pattern are:

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 the Builder interface
Product
represents the complex object under construction. ConcreteBuilder builds the product's internal representation and definesthe process by which it's assembled includes classes that define the constituent parts, including interfaces for assembling the parts into the final result

Case study

Consider we have to create two types of report say, PDF report and XLS report. both this report building process/construction is complex but they have similar set of operation sequence like data fetching, template fetching, mapping data. generation of the final report with desired extension type. this is an ideal case where we can use builder pattern.

Here the classes and interfaces are:

 

Builder = RepotBuilder

ConcreteBuilder = PDFReportBuilder/XLReportBuilder

Director = ReportDirector

Product = Report

Download Sample Code

Comments

mahmud's picture

Good post! If you could give some real life example out of the software world, it could have been more easy for people who are new to know about this. But really, this writing is a good post to explain the pattern in simple way. Loved it!

Add new comment