mercredi 27 février 2019

Using the Step Builder pattern for the creation of a complex object that contains an instance variable that is a list

Let's say I want to construct an instance of the following object:

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

I'm trying to use the Step Builder pattern to construct this object, so that a user sets the value of the parameters in order. The main problem that I'm facing is with creating an interface for the last step. I want to expose the build() method after the user has provided atleast one integer that I can add in listParam4. At the same time I also want to give the user the option of providing more integers to add to the list before calling the build() method. I would really appreciate if someone can provide me a way of doing this or suggest an alternative approach in case I'm approaching this problem incorrectly.

Here is the code that I currently have to achieve this:

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

Aucun commentaire:

Enregistrer un commentaire