Tuesday, July 6, 2021

Builder design pattern ?

 This is a type of creational design pattern where user can create object without specifying all the parameter of the constructor to build the object using a builder .

Advantage:

1.No need to specify all the parameter into constructor .

2.No need to maintain parameter sequence in constructor .

3.User can create object by their need .

Ex:

PC class:

public class PC {

private String ram;

private String processor;

private String hdd;

private String motherBoard;


public PC(String ram, String processor, String hdd, String motherBoard) {

super();

this.ram = ram;

this.processor = processor;

this.hdd = hdd;

this.motherBoard = motherBoard;

}

@Override

public String toString() {

return "PC [ram=" + ram + ", processor=" + processor + ", hdd=" + hdd + ", motherBoard=" + motherBoard + "]";

}

}

Builder class:

package builderDesignPatternImplementation;

public class PcBuilder {
private String ram;
private String processor;
private String hdd;
private String motherBoard;

public PcBuilder setRam(String ram) {
this.ram = ram;
return this;
}

public PcBuilder setProcessor(String processor) {
this.processor = processor;
return this;
}

public PcBuilder setHdd(String hdd) {
this.hdd = hdd;
return this;
}

public PcBuilder setMotherBoard(String motherBoard) {
this.motherBoard = motherBoard;
return this;
}

public PC getPC() {
return new PC(ram, processor, hdd, motherBoard);
}
}

Main App:

public class MainApp {

public static void main(String[] args) {

PcBuilder builder = new PcBuilder();
PC pc = builder.setProcessor("core i7").setHdd("samsung").getPC();
System.out.println(pc.toString());
}

}

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...