How to Implement Builder Design Pattern in Java


In this example, let’s see how to implement Builder Pattern in Java.

Source Code

package com.beginner.examples;

//product
class Product {  
    private String pc;  
    private String mouse;  
    private String keyboard;  
  
    void setPc(String pc) { 
    	this.pc = pc;
    }  
    void setMouse(String mouse) { 
    	this.mouse = mouse; 
    }  
    void setKeyboard(String keyboard) { 
    	this.keyboard = keyboard;
    }  
  
    String show() { 
    	return "pc: " + pc + "; keyboard: " + keyboard + "; mouse: " + mouse ; 
    }  
}  
  
//builder interface
interface Builder {  
    void setPc(String pc);  
    void setMouse(String mouse);  
    void setKeyboard(String keyboard);  
    Product build();  
}  
  
//implement builder interface 
class ConcreteBuilder implements Builder {  
    private Product p = new Product();  
  
    @Override public void setPc(String pc) { 
    	p.setPc(pc); 
    }  
    @Override public void setMouse(String mouse) { 
    	p.setMouse(mouse); 
    }  
    @Override public void setKeyboard(String keyboard) { 
    	p.setKeyboard(keyboard); 
    }  
    @Override public Product build() {
    	return p;
    }  
}  
  
//create product
class Director {  
    private Builder b = null;  
    Director(Builder builder) { 
    	this.b = builder; 
    }  
    Product createProduct(String pc, String mouse, String keyboard) {  
        this.b.setPc(pc);  
        this.b.setMouse(mouse);  
        this.b.setKeyboard(keyboard);  
        return b.build();  
    }  
}  
  
public class BuilderExample {  
    public static void main(String[] args) {  
        Builder builder = new ConcreteBuilder();  
        Director director = new Director(builder);  
        Product p =  director.createProduct("Apple","Logitech","Razer");  
        System.out.println(p.show());  
    }  
}

Output:

pc: Apple; keyboard: Razer; mouse: Logitech
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments