假设我想构造以下对象的实例:
private class ComplexObject {
private int param1; // Required Parameter
private int param2; // Required Parameter
private int param3; // Required Parameter
private List<Integer> listParam4; // This list should contain atleast one Integer
private ComplexObject() {
this.listParam4 = new ArrayList<Integer>();
}
}
我正在尝试使用Step Builder模式构造此对象,以便用户按顺序设置参数的值。我面临的主要问题是为最后一步创建一个界面。我希望在用户提供至少一个我可以在build()
中添加的整数后公开listParam4
方法。同时我还想让用户在调用build()
方法之前提供更多整数来添加到列表中。我真的很感激,如果有人能为我提供一种方法,或者建议我采用其他方法,以防我错误地解决这个问题。
这是我目前要实现的代码:
public interface SetParam1Step {
SetParam2Step setParam1(int param1);
}
public interface SetParam2Step {
SetParam3Step setParam2(int param2);
}
public interface SetParam3Step {
AddToParam4ListStep setParam3(int param3);
}
public interface AddToParam4ListStep {
// Not sure how to create this interface
}
public static class ComplexObjectBuilder implements SetParam1Step, SetParam2Step, SetParam3Step, AddToParam4ListStep {
private int param1;
private int param2;
private int param3;
private List<Integer> listParam4;
private ComplexObjectBuilder() {
// Prevent Instantiation
}
@Override
public AddToParam4ListStep setParam3(int param3) {
this.param3 = param3;
return this;
}
@Override
public SetParam3Step setParam2(int param2) {
this.param2 = param2;
return this;
}
@Override
public SetParam2Step setParam1(int param1) {
this.param1 = param1;
return this;
}
// Needs to implement the build() method and the methods that would eventually be added to the AddToParam4ListStep interface.
public static SetParam1Step newInstance() {
return new ComplexObjectBuilder();
}
}
AddToParam4ListStep
应该只是有一个add()
方法返回另一个接口(AddToParam4ListOrBuild
),它将允许add()
更多参数(返回自己)并构建最终对象:
public interface AddToParam4ListStep {
AddToParam4ListOrBuild add(Integer toAdd);
}
public interface AddToParam4ListOrBuild {
AddToParam4ListOrBuild add(Integer toAdd);
ComplexObject build();
}