Builder 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.
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.
“Separate the construction of a complex object from its representation so that the same construction process can create different representations”
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.
public class BuilderPatternExample {
public static void main(String args[]) {
//Creating object using Builder pattern in java
Cake whiteCake = new Cake.Builder().sugar(1).butter(0.5). eggs(2).vanila(2).flour(1.5). bakingpowder(0.75).milk(0.5).build();
//Cake is ready to eat :)
System.out.println(whiteCake);
}
}
class Cake {
private final double sugar; //cup
private final double butter; //cup
private final int eggs;
private final int vanila; //spoon
private final double flour; //cup
private final double bakingpowder; //spoon
private final double milk; //cup
private final int cherry;
public static class Builder {
private double sugar; //cup
private double butter; //cup
private int eggs;
private int vanila; //spoon
private double flour; //cup
private double bakingpowder; //spoon
private double milk; //cup
private int cherry;
//builder methods for setting property
public Builder sugar(double cup){this.sugar = cup; return this; }
public Builder butter(double cup){this.butter = cup; return this; }
public Builder eggs(int number){this.eggs = number; return this; }
public Builder vanila(int spoon){this.vanila = spoon; return this; }
public Builder flour(double cup){this.flour = cup; return this; }
public Builder bakingpowder(double spoon){this.sugar = spoon; return this; }
public Builder milk(double cup){this.milk = cup; return this; }
public Builder cherry(int number){this.cherry = number; return this; }
//return fully build object
public Cake build() {
return new Cake(this);
}
}
//private constructor to enforce object creation through builder
private Cake(Builder builder) {
this.sugar = builder.sugar;
this.butter = builder.butter;
this.eggs = builder.eggs;
this.vanila = builder.vanila;
this.flour = builder.flour;
this.bakingpowder = builder.bakingpowder;
this.milk = builder.milk;
this.cherry = builder.cherry;
}
@Override
public String toString() {
return "Cake{" + "sugar=" + sugar + ", butter=" + butter + ", eggs=" + eggs + ", vanila=" + vanila + ", flour=" + flour + ", bakingpowder=" + bakingpowder + ", milk=" + milk + ", cherry=" + cherry + '}';
}
}
Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}
Builder design pattern in Java – Pros and ConsLive everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.
Advantages:
1) more maintainable if number of fields required to create object is more than 4 or 5.
2) less error-prone as user will know what they are passing because of explicit method call.
3) more robust as only fully constructed object will be available to client.
Disadvantages:
1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.
When to use Builder Design pattern in JavaBuilder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don't confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.
That's all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go.
Applicability & Examples
Builder Pattern is used when:
the creation algorithm of a complex object is independent from the parts that actually compose the object
the system needs to allow different representations for the objects that are being built
Example 1 - Vehicle Manufacturer.
Let us take the case of a vehicle manufacturer that, from a set of parts, can build a car, a bicycle, a motorcycle or a scooter. In this case the Builder will become the VehicleBuilder. It specifies the interface for building any of the vehicles in the list above, using the same set of parts and a different set of rules for every type of type of vehicle. The ConcreteBuilders will be the builders attached to each of the objects that are being under construction. The Product is of course the vehicle that is being constructed and the Director is the manufacturer and its shop.
Example 1 - Students Exams.
If we have an application that can be used by the students of a University to provide them with the list of their grades for their exams, this application needs to run in different ways depending on the user that is using it, user that has to log in. This means that, for example, the admin needs to have some buttons enabled, buttons that needs to be disabled for the student, the common user. The Builder provides the interface for building form depending on the login information. The ConcreteBuilders are the specific forms for each type of user. The Product is the final form that the application will use in the given case and the Director is the application that, based on the login information, needs a specific form.
Specific problems and implementation
Builder and Abstract Factory
The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That�s why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory�s methods to create its own objects. In the Builder�s case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.
Common interface for products
In practice the products created by the concrete builders have a structure significantly different, so if there is not a reason to derive different products a common parent class. This also distinguishes the Builder pattern from the Abstract Factory pattern which creates objects derived from a common type.
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.
“Separate the construction of a complex object from its representation so that the same construction process can create different representations”
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.
public class BuilderPatternExample {
public static void main(String args[]) {
//Creating object using Builder pattern in java
Cake whiteCake = new Cake.Builder().sugar(1).butter(0.5). eggs(2).vanila(2).flour(1.5). bakingpowder(0.75).milk(0.5).build();
//Cake is ready to eat :)
System.out.println(whiteCake);
}
}
class Cake {
private final double sugar; //cup
private final double butter; //cup
private final int eggs;
private final int vanila; //spoon
private final double flour; //cup
private final double bakingpowder; //spoon
private final double milk; //cup
private final int cherry;
public static class Builder {
private double sugar; //cup
private double butter; //cup
private int eggs;
private int vanila; //spoon
private double flour; //cup
private double bakingpowder; //spoon
private double milk; //cup
private int cherry;
//builder methods for setting property
public Builder sugar(double cup){this.sugar = cup; return this; }
public Builder butter(double cup){this.butter = cup; return this; }
public Builder eggs(int number){this.eggs = number; return this; }
public Builder vanila(int spoon){this.vanila = spoon; return this; }
public Builder flour(double cup){this.flour = cup; return this; }
public Builder bakingpowder(double spoon){this.sugar = spoon; return this; }
public Builder milk(double cup){this.milk = cup; return this; }
public Builder cherry(int number){this.cherry = number; return this; }
//return fully build object
public Cake build() {
return new Cake(this);
}
}
//private constructor to enforce object creation through builder
private Cake(Builder builder) {
this.sugar = builder.sugar;
this.butter = builder.butter;
this.eggs = builder.eggs;
this.vanila = builder.vanila;
this.flour = builder.flour;
this.bakingpowder = builder.bakingpowder;
this.milk = builder.milk;
this.cherry = builder.cherry;
}
@Override
public String toString() {
return "Cake{" + "sugar=" + sugar + ", butter=" + butter + ", eggs=" + eggs + ", vanila=" + vanila + ", flour=" + flour + ", bakingpowder=" + bakingpowder + ", milk=" + milk + ", cherry=" + cherry + '}';
}
}
Output:
Cake{sugar=0.75, butter=0.5, eggs=2, vanila=2, flour=1.5, bakingpowder=0.0, milk=0.5, cherry=0}
Builder design pattern in Java – Pros and ConsLive everything Builder pattern also has some disadvantages, but if you look at below, advantages clearly outnumber disadvantages of Builder design pattern. Any way here are few advantages and disadvantage of Builder design pattern for creating objects in Java.
Advantages:
1) more maintainable if number of fields required to create object is more than 4 or 5.
2) less error-prone as user will know what they are passing because of explicit method call.
3) more robust as only fully constructed object will be available to client.
Disadvantages:
1) verbose and code duplication as Builder needs to copy all fields from Original or Item class.
When to use Builder Design pattern in JavaBuilder Design pattern is a creational pattern and should be used when number of parameter required in constructor is more than manageable usually 4 or at most 5. Don't confuse with Builder and Factory pattern there is an obvious difference between Builder and Factory pattern, as Factory can be used to create different implementation of same interface but Builder is tied up with its Container class and only returns object of Outer class.
That's all on Builder design pattern in Java. we have seen why we need Builder pattern , what problem it solves, Example of builder design pattern in Java and finally when to use Builder patter with pros and cons. So if you are not using telescoping constructor pattern or have a choice not to use it than Builder pattern is way to go.
Applicability & Examples
Builder Pattern is used when:
the creation algorithm of a complex object is independent from the parts that actually compose the object
the system needs to allow different representations for the objects that are being built
Example 1 - Vehicle Manufacturer.
Let us take the case of a vehicle manufacturer that, from a set of parts, can build a car, a bicycle, a motorcycle or a scooter. In this case the Builder will become the VehicleBuilder. It specifies the interface for building any of the vehicles in the list above, using the same set of parts and a different set of rules for every type of type of vehicle. The ConcreteBuilders will be the builders attached to each of the objects that are being under construction. The Product is of course the vehicle that is being constructed and the Director is the manufacturer and its shop.
Example 1 - Students Exams.
If we have an application that can be used by the students of a University to provide them with the list of their grades for their exams, this application needs to run in different ways depending on the user that is using it, user that has to log in. This means that, for example, the admin needs to have some buttons enabled, buttons that needs to be disabled for the student, the common user. The Builder provides the interface for building form depending on the login information. The ConcreteBuilders are the specific forms for each type of user. The Product is the final form that the application will use in the given case and the Director is the application that, based on the login information, needs a specific form.
Specific problems and implementation
Builder and Abstract Factory
The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That�s why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory�s methods to create its own objects. In the Builder�s case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.
Common interface for products
In practice the products created by the concrete builders have a structure significantly different, so if there is not a reason to derive different products a common parent class. This also distinguishes the Builder pattern from the Abstract Factory pattern which creates objects derived from a common type.