Builder Pattern in Java to avoid multiple argument constructors for the same object

This post is heavily inspired by page 14, chapter 2 of Joshua Bloch’s Effective Java Second Edition. I typed it out here as an exercise to memorise it.

The idea of this pattern is to implement a better way of creating an object which has optional parameters. For example, a Dog object in a database needs to have a name attribute. However, breed, age and colour attributes are optional. Consider the old constructor setup, and by old I mean the way I coded it before I discovered the Builder pattern:

public class Dog{

       public Dog(String name){…}

       public Dog(String name, String breed){…}

       public Dog(String name, String breed, int age, String colour){…}

etc, etc,

Not very efficient, the following is an example of the Builder Pattern

public class Dog{

 private final String name;       

 private final String breed;

 private final String colour;

public static class Builder{

//required parameter
private final String name;

//optional parameters
private final String breed = “”
private final String colour = “”

public Builder(String name){
this.name = name;
}

public Builder breed(String val)
{ breed = val; return this;}

public Builder breed(String val)

{ colour= val; return this;}

public Dog build(){
return new Dog(this);
}

private Dog(Builder builder){
breed = builder.breed;
colour = builder.colour;
}
}

The object of type Dog is then created as such:

Dog arsenesDog = new Dog.Builder(“Thierry”).breed(“lab”).colour(“golden”).build();

thierry-henry

Thierry Henry, an evangelist for the Builder Pattern