我正在开发一个需要构建复合对象的java项目。简而言之,我正在使用Builder Pattern的变体来构建“实验”。我还需要创建一个构建器,以便从实验模型中的实验用户字段创建用户。
问题在于,当我构建实验时,我不确定如何设计Composite Design Pattern对象来构建
experiment.users
。
与该主题没有密切关系,但我在前端使用SpringMVC并使用JPA作为持久层......
The Service
public interface ExperimentService {
public Experiment create( ExperimentDTO created );
...
}
The Controller
@RequestMapping(value = "/experiment/create", method = RequestMethod.POST)
public String submitCreateExperimentForm(@Valid @ModelAttribute(MODEL_ATTRIBUTE_EXPERIMENT) ExperimentDTO created, BindingResult bindingResult, RedirectAttributes attributes) {
...
Experiment experiment = experimentService.create(created);
...
}
尝试遵循良好的设计习惯,我尝试通过遵循实验实体中的经典构建器模式来避免构建Anemic Domain Model。但是,我在确定从ExperimentBuilder调用我的UserBuilder Builder的最佳工作流程时有点困难......
The Builder
public interface Builder<T> {
public T build();
}
Experiment Entity
@Entity(name = "experiment")
public class Experiment implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany
@JoinTable(
name = "experiment_participant",
joinColumns = @JoinColumn( name = "experiment_id"),
inverseJoinColumns = @JoinColumn( name = "participant_id")
)
private Set<ExperimentUser> experimentUsers = new HashSet<>();
/** fields ... getters ... setters .. **/
public static class ExperimentBuilder implements Builder {
private final Experiment experiment;
/** fields ... **/
public ExperimentBuilder( ... ) {
experiment = new Experiment();
/** ??? WIRE UP THE USERBUILDER HERE ??? ** **/
}