Adding elements to ArrayList using builder pattern in Java

13,709

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();
Share:
13,709
Mac
Author by

Mac

Updated on June 04, 2022

Comments

  • Mac
    Mac almost 2 years

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