我正在尝试将元素添加到ArrayList<Movements>movement
作为构建器模式的一部分。
Movement类包含int movementId
和String movementName
,我希望用户使用构建器模式将这些添加到合成中。
我正在努力实施,见下文:
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);
}
}
我希望能够使用
构建合成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);
}
}
组合构造函数:
private Composition(CompositionBuilder builder){
this.compositionId = builder.compositionId;
this.movement = builder.movement;
this.compositionName = builder.compositionName;
this.composerName = builder.composerName;
}
答案 0 :(得分:2)
使用CompositionBuilder创建Movement实例将违反SRP(您需要修改构建器中movement
方法的签名)。相反,您应该将Movement的实例传递给movement(Movement...movements)
方法,调用构造函数或工厂
Composition composition1 = new Composition.CompositionBuilder("1", "CompositionOne", "John Doe")
.movement(Movement.newInstance(id, name), Movement.newInstance(id2, name2))
.build();