Below is my Builder pattern class which generates an Employee Object.
public class Employee {
// required parameters
private String HDD;
private String RAM;
// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
private Employee(EmployeeBuilder builder) {
this.HDD=builder.HDD;
this.RAM=builder.RAM;
this.isGraphicsCardEnabled=builder.isGraphicsCardEnabled;
this.isBluetoothEnabled=builder.isBluetoothEnabled;
}
public static class EmployeeBuilder {
private String HDD;
private String RAM;
// optional parameters
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public EmployeeBuilder(String hdd, String ram){
this.HDD = hdd;
this.RAM = ram;
}
public EmployeeBuilder isGraphicsCardEnabled(Boolean isGraphicsCardEnabled){
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}
public EmployeeBuilder isBluetoothEnabled(boolean isBluetoothEnabled){
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}
public Employee build(){
return new Employee(this);
}
}
public static void main(String args[]){
Employee emp = new Employee.EmployeeBuilder("500", "64").
isGraphicsCardEnabled(true).
isGraphicsCardEnabled(true).build();
System.out.println(emp.HDD);
System.out.println(emp.getHDD());
}
}
A builder whose parameters have been set makes a fine Abstract Factory [Gamma95, p. 87]
. In other words, a client can pass such a builder
to a method to enable the method to create one or more objects for the client. To enable this usage, you need a type to represent the builder. If you are using release 1.5 or a later release, a single generic type (Item 26)
suffices for all builders, no matter what type of object they’re building.
Can anyone add some light on the above paragraph with an working example. I am not able to understand the above para which is taken from Effective Java - Joshua Bloch.