下面是我的Builder模式类,它生成一个Employee对象。
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());
}
}
已设置参数的构建器可以很好地Abstract Factory [Gamma95, p. 87]
。换句话说,客户端可以将这样的builder
传递给方法,以使该方法能够为客户端创建一个或多个对象。要启用此用法,您需要一个类型来表示构建器。如果您使用的是1.5版或更高版本,则single generic type (Item 26)
足以满足所有构建器的需要,无论他们正在构建什么类型的对象。
任何人都可以通过一个工作示例在上面的段落中添加添加一些亮点。我无法理解上面的段落取自 Effective Java - Joshua Bloch 。