Builder Design Pattern

Hi Geeks, in this tutorial we will focus on the Builder Design Pattern. So let’s get started!

Concepts :

  • Handles complex constructors
  • Large number of parameters
  • Immutability

Examples of builders in the Java language: StringBuilder and the DocumentBuilder.

So, one of the problems solved by Builder is when you want to have different ways to construct an object and at the same time you want to make the object immutable (no one can change its values; no setters).

The intent of the Builder Pattern is to separate the complex construction of the object from its representation. So that the same construction process can be used to build different representations.

Let’s look into an example and how we can solve it using Builder.

Example : 

Let’s suppose that we want to create a sandiwch with the following ingredients: meat, mayonnaise , cheese and tomato.

The sandwich class :

public class Sandwich {

	
	private String meat;
	private String mayonnaise;
	private String cheese;
	private String tomato;
	
	// the first constructor with all the ingredients 
	public Sandwich(String meat, String mayonnaise, String cheese, String tomato) {
		super();
		this.meat = meat;
		this.mayonnaise = mayonnaise;
		this.cheese = cheese;
		this.tomato = tomato;
	}
	
	// constructor with only meat
	public Sandwich(String meat) {
		this.meat = meat;
	}
	// constructor with meat and cheese 
	public Sandwich(String meat,String cheese) {
		this.cheese = cheese;

	}
	
	// if you want to add another constructor for different types ;
          //  You may want to use Builder ! 
	
	public String getMeat() {
		return meat;
	}
	public String getMayonnaise() {
		return mayonnaise;
	}
	public String getCheese() {
		return cheese;
	}
	public String getTomato() {
		return tomato;
	}
		
	
}

The main class :

    public static void main(String[] args) {
	
        Sandwich sandwich1 = new Sandwich("meat","cheese");
        
        /*what if i want to add tomato to sandiwch1 ;
         We do not have a setter because the object is
         immutable . We add onther constructor? No , Builder is the solution */

    }

The SandwitchBuilder :

  public class Sandwich {


      // an inner static class that represents the builder      
      public   static class SandiwchBuilder {
          private String meat;
          private String mayonnaise;
          private String cheese;
          private String tomato;

            // empty constructor
          public SandiwchBuilder() {

          }
          
          
                // the build method will build our Sandwich object ; 
                // you can name it whatever you want just build is convention 
            public Sandwich build() {
              return  new Sandwich(this);
            }
            
            
            // Each of the methods below will return A SandwichBuilder 
             // ; you will see why in the main class !

            public  SandiwchBuilder meat(String meat) {
              this.meat = meat;
              return  this;
            }

          public  SandiwchBuilder mayonnaise(String mayonnaise) {
              this.mayonnaise = mayonnaise;
              return  this;
          }

          public  SandiwchBuilder cheese(String cheese) {
              this.cheese = cheese;
              return  this;
          }
          public  SandiwchBuilder tomato(String tomato) {
              this.tomato = tomato;
              return  this;
          }



        }



        private String meat;
        private String mayonnaise;
        private String cheese;
        private String tomato;

      // the sandwich constructor takes the builder as a parameter 
        
      public   Sandwich(SandiwchBuilder builder) {
            this.cheese = builder.cheese;
            this.mayonnaise = builder.mayonnaise;
            this.meat = builder.meat;
            this.tomato = builder.tomato;
        }


        public String getMeat() {
            return meat;
        }
        public String getMayonnaise() {
            return mayonnaise;
        }
        public String getCheese() {
            return cheese;
        }
        public String getTomato() {
            return tomato;
        }


    }

The main class  :

 public static void main(String[] args) {
        
        // instantiate the builder     
        Sandwich.SandiwchBuilder  sandiwchBuilder = new Sandwich.SandiwchBuilder();
        
        // Builder please create a sandwich for me ! 
        sandiwchBuilder.cheese("cheese").mayonnaise("mayonnaise"); 
   // cheese() returns a SandwichBuilder so we can directly chained with other methods .  
     // as you can see the creation is handled by the builder ,you want to add 
      // tomato no problem
      sandichBuilder.tomato("tomato");
        
        // return a Sandwich by calling the build() method 
        Sandwich sandwich = sandiwchBuilder.build();

    }

 

And That’s It for this tutorial. I hope you learned the pattern. The more you practice the more you get it .

                  Happy coding!