Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements to ArrayList using builder pattern in Java

I am trying to add elements to ArrayList<Movements>movement as part of a builder pattern.

The Movement class contains an int movementId and a String movementName and I would like the user to add these to the composition using the builder pattern.

I am struggling with the implementation, see below:

public static class CompositionBuilder {
    private final String compositionId;
    private List<Movements> movement = new ArrayList<Movements>();
    private final String compositionName;
    private final String composerName;

    public CompositionBuilder(String compositionId,
                              String compositionName,
                              String composerName) {
        this.compositionId = compositionId;
        this.compositionName = compositionName;
        this.composerName = composerName;
    }

    //this part is where I am struggling.
    //I don't know how to populate the ArrayList
    public CompositionBuilder movement(Movements... movement) {
        for (Movements i : movement) {
            this.movement.add(i);
        }
        return this;
    }

    public Composition build() {
        return new Composition(this);
    }
}

I want to be able to build the composition using

public class CompositionBuilderTest {
    public static void main(String[] args) {
        Composition composition1 = new Composition
                .CompositionBuilder("1", "CompositionOne", "John Doe")
                .movement()//enter movement values here
                .build();
        System.out.println(composition1);
    }
}

Composition Constructor:

private Composition(CompositionBuilder builder) {
    this.compositionId = builder.compositionId;
    this.movement = builder.movement;
    this.compositionName = builder.compositionName;
    this.composerName = builder.composerName;
}
like image 488
Mac Avatar asked Oct 23 '25 14:10

Mac


1 Answers

Using the CompositionBuilder to create instances of Movement would go against SRP (and you would need to modify the signature of the movement method in the builder). Rather, you should pass instances of Movement into the movement(Movement...movements) method, calling either a constructor or a factory

Composition composition1 = new Composition
      .CompositionBuilder("1", "CompositionOne", "John Doe")
      .movement(Movement.newInstance(id, name), Movement.newInstance(id2, name2))
      .build();
like image 77
nomis Avatar answered Oct 26 '25 04:10

nomis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!