Thursday, November 23, 2017

Builder design pattern simple example

The below is normal simple class with constructor.

public class Computer {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public Computer(String modelname, int ram, String keyboardName, String mouseName) {
		super();
		this.modelname = modelname;
		this.ram = ram;
		this.keyboardName = keyboardName;
		this.mouseName = mouseName;
	}

	@Override
	public String toString() {
		return "Computer [modelname=" + modelname + ", ram=" + ram + ", keyboardName=" + keyboardName + ", mouseName="
				+ mouseName + "]";
	}
}

You have another one main class called JavaTest is below.

public class JavaTest{
public static void main(String args[]){
Computer comp = new Computer("Intel", 6, "Logitech", "dell");
System.out.println("Comp object is: " + comp );
}
}

Output:
Comp object is: Computer [modelname=Intel, ram=6, keyboardName=Logitech, mouseName=dell]


We can change the above code to Builder design pattern. To do this you need to create one additional class called ComputerBuilder.

public class ComputerBuilder {

	private String modelname="";
	private int ram = 0;
	private String keyboardName= "";
	private String mouseName = "";
	
	public ComputerBuilder setModelname(String modelname) {
		this.modelname = modelname;
		return this;
	}
	public ComputerBuilder setRam(int ram) {
		this.ram = ram;
		return this;
	}
	public ComputerBuilder setKeyboardName(String keyboardName) {
		this.keyboardName = keyboardName;
		return this;
	}
	public ComputerBuilder setMouseName(String mouseName) {
		this.mouseName = mouseName;
		return this;
	}
	
	public Computer getComputer () {
		return new Computer(modelname, ram, keyboardName, mouseName);
	}
}

From the above class,

1. It don't have any getter method. We have added only setter method.

2. The last method getComputer returning the object of Computer class.

Let see how we can execute this code from main class.

Computer c = new ComputerBuilder().setKeyboardName("DELL KEyboard").setMouseName("LOGI Mouse").getComputer();
System.out.println("Comp object from builder design pattern is : " + c );

You can notice from the main class,

1. You wont get complex for creating object for computer.

2. Its not mandatory to put all arguments. If you are not providing arguments it will take its initial initialized value.

3. It will be more clear than our normal code creating object through constructor.

Output:
Comp object from builder design pattern is : Computer [modelname=, ram=0, keyboardName=DELL KEyboard, mouseName=LOGI Mouse]