jeudi 12 mars 2015

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

Aucun commentaire:

Enregistrer un commentaire