要求在 Java 构建器中填充字段具有某些模式


class Builder {
private Foo myItem = new Foo();
public Builder field1(Bar val) {
myItem.setField1(val);
return this;  
}
public Builder field2(Baz val) {
myItem.setField2(val);
return this;  
}
public Builder field3(Gaz val) {
myItem.setField3(val);
return this;  
}
public Foo build() {
return myItem;
}
}

假设对于我上面的类,我希望所有字段,或字段 1 和字段 2 一起填充,或者只填充字段 3。

public Foo build() throws Exception {
if ((myItem.getField1() == null || myItem.getField2() == null) && myItem.getField3() == null) {    
throw new Exception();
}
return myItem;
} 

这实现了目标,尽管以一种非常冗长和难以理解的方式。实现同一目标的更好方法是什么:使字段模式成为强制性的?

答案很简单。您应该将字段 1、2 和 3 分隔到两个单独的类中。

当你说对象有field1和field2或field3时,你有两个不同的类。

这个想法怎么样:有两个构建器继承自一个 Builder 类?

父类将 field1 和 field2 委托给一个实现,将 field3 委托给另一个实现。

这是代码。

public class Builder {
protected Object myItem = new Object();
private Field12Builder field12Builder = new Field12Builder(myItem);
private Field3Builder field3Builder = new Field3Builder(myItem);
public Builder field1(Object val) throws Exception {
return field12Builder.field1(val);
}
public Builder field2(Object val) throws Exception {
return field12Builder.field2(val);
}
public Builder field3(Object val) throws Exception {
return field3Builder.field3(val);
}
public Object build() throws Exception {
return myItem;
}
}

public class Field12Builder extends Builder {
public Field12Builder(Object myItem) {
this.myItem = myItem;
}
public Builder field1(Object val) {
myItem.setField1(val);
return this;
}
public Builder field2(Object val) {
myItem.setField2(val);
return this;
}
public Builder field3(Object val) throws Exception {
throw new Exception("Cannot have field3 if field1 or field2 is valorized.");
}
public Object build() throws Exception {
if (myItem.getField1() == null || myItem.getField2() == null) {
throw new Exception("field1 and field2 must be both valorized.");
}
return super.build();
}
}

public class Field3Builder extends Builder {
public Field3Builder(Object myItem) {
this.myItem = myItem;
}
public Builder field1(Object val) throws Exception {
throw new Exception("Cannot have field1 if field3 is valorized.");
}
public Builder field2(Object val) throws Exception {
throw new Exception("Cannot have field2 if field3 is valorized.");
}
public Builder field3(Object val) {
myItem.setField3(val);
return this;
}
public Object build() throws Exception {
return super.build();
}
}

最新更新