首先发布在这里。
我在构建一个有点复杂的实体时遇到了麻烦。
首先让我简要解释一下这个模型。
活动是一种规范。它定义了练习及其说明。该规范可以在不同的活动序列中重复使用。
作为聚合根,我有ActivitySequence。它定义了一个人也必须按照每个步骤中定义的适当日间隔执行的步骤,也是可重复使用的步骤序列。 标准序列可以包含所有类型的活动。 RunningSequence只能包含运行活动的步骤。它还定义了可以执行这些运行步骤的日期以及此人在此RunningSequence之后必须启动的下一个ActivitySequence
注意:这不是我公司的实际业务领域。我创建了一个模拟模型,这样就不会让公司暴露出必需品。
我将首先尝试创建一个静态工厂方法来创建特定类型。
首先,我想知道我是否在正确的道路结构上明智。
鉴于此模型:
如何创建活动序列对象?我把代码放在哪里?在一个单独的工厂?域名服务?
编辑:
我认为更好的问题是:
我应该在Step中引用Activity对象还是只引用id? 如果我只有Id,我应该在哪里检查/验证活动是否都来自特定的序列类型? 我应该创建一个子类型RunningStep,以便RunningSequence在其构造中只接受RunningStep吗?
谢谢!
public class Activity {
private ActivityId id;
private String instructions;
private Exercise exercise;
public Exercise exercise() {
return exercise;
}
public enum Exercise {
RUNNING,
SWIMMING,
PUSH_UP,
PULL_UP,
SQUAT,
}
}
public class SequenceStep {
private int daysFromPreviousStep;
private Activity activity;
protected SequenceStep(Activity activity, int daysFromPreviousStep) {
this.daysFromPreviousStep = daysFromPreviousStep;
this.activity = activity;
}
public Activity activity() {
return activity;
}
}
public class ActivitySequence {
private ActivitySequenceId id;
private String title;
private List<SequenceStep> steps;
protected ActivitySequence(String title, List<SequenceStep> steps) {
this.setTitle(title);
this.setSequenceSteps(steps);
}
public static ActivitySequence createStandardSequence(String title,, List<Activity> activities) {
return new ActivitySequence(title, steps);
}
public static ActivitySequence createRunningSequence(String title,
List<SequenceStep> steps,
Set<DayOfWeek> daysCanBePerformed,
ActivitySequenceId nextActivitySequenceId) {
return new RunningSequence(title, activities, daysCanBePerformed, trigger, destinationCadenceId);
}
private void setTitle(String title) {
Validate.notBlank(title, "Title is required");
this.title = title;
}
private void setSequenceSteps(List<SequenceStep> steps) {
Validate.notEmpty(steps, "A minimum of 1 step is required");
this.steps = steps;
}
}
public class RunningSequence extends ActivitySequence {
private Set<DayOfWeek> daysCanBePerformed;
private ActivitySequenceTemplateId nextActivitySequenceId;
protected RunningSequence(String title,
List<SequenceStep> sequenceSteps,
Set<DayOfWeek> daysCanBePerformed,
) {
super(title, description, activities);
boolean onlyRunningActivities = activities.stream().allMatch(sequenceStep -> sequenceStep.activity().exercise().equals(Activity.Exercise.RUNNING));
Validate.isTrue(onlyRunningActivities, "Only running activity allowed in sequence");
this.setDaysCanBePerformed(daysCanBePerformed);
}
private void setDaysCanBePerformed(Set<DayOfWeek> daysCanBePerformed) {
Validate.notEmpty(daysCanBePerformed, "A minimum of 1 day is required");
this.daysCanBePerformed = daysCanBePerformed;
}
}