使用“步骤构建器”模式创建包含实例变量(列表)的复杂对象

时间:2019-02-28 06:56:14

标签: java design-patterns builder

假设我要构造以下对象的实例:

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>();
    }
}

我正在尝试使用“步骤构建器”模式来构造此对象,以便用户按顺序设置参数的值。我面临的主要问题是为最后一步创建接口。我想在用户提供了至少一个我可以在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();
    }
}

1 个答案:

答案 0 :(得分:1)

AddToParam4ListStep应该简单地具有一个add()方法,该方法返回另一个接口(AddToParam4ListOrBuild),该接口将允许add()更多参数(返回自身)并构建最终对象:

public interface AddToParam4ListStep {
    AddToParam4ListOrBuild add(Integer toAdd);
}

public interface AddToParam4ListOrBuild {
    AddToParam4ListOrBuild add(Integer toAdd);
    ComplexObject build();
}