假设我有一个从另一个类继承的类:
class Parent{
private String p1;
public void setP1(String p1){
this.p1 = p1;
}
}
class Child extends Parent{
private int c1;
public void setP1(int c1){
this.c1 = c1;
}
}
我使用构建器模式创建父类的实例:
class ParentBuilder{
aParent(){ return new ParentBuilder()}
with(String p1){
this.p1 = p1;
}
public Parent build(){
Parent parent = new Parent();
parent.setP1(this.p1);
return parent;
}
}
如何使用Child类的构建器模式执行类似的操作
aParent().with(3).with("test").build();
aParent().with("test").with(3).build();
aChild().with(4).build();
aChild().with(4).with("test").build();
aChild().with("test").with(4).build();
[约书亚·布洛赫(Joshua Bloch)的著作《有效的Java》中有一个很好的例子。尝试将ParentBuilder作为公共静态类移到Parent内部,并构建此way。