我有这些实体
我设计了聚合根,如下所示
聚合根
我正朝着正确的方向前进吗?
答案 0 :(得分:1)
是的,听起来很对。这是我在c#中的即兴创作:
//aggregate root
public class User{/*first name, last name, contacts, etc.*/}
//aggregate root
public class Project{
public IList Tasks{get; private set;}
public User CreatedBy{get; private set;}
public Project(User createdBy){
CreatedBy=createdBy;
}
public RegisterTask(string taskDescription, User assignedTo){
Tasks.Add(new Task(taskDescription, assignedTo));
}
public StartWorkOn(Task task){
if(!Tasks.Contains(task))
throw new Exception("Task is not registered");
task.StartWork();
}
}
//entity
public class Task{
public User AssignedTo{get;private set;}
public string Description{get; private set;}
public TaskStatus Status{get; private set;}
internal Task(string description, User assignedTo){
AssignedTo=assignedTo;
Description=description;
Status=TaskStatus.Pending;
}
internal void StartWork(){
if(Status!=TaskStatus.Pending)
throw new Exception("Can't start what's ongoing");
Status=TaskStatus.InProgress;
}
internal void Finish(){
if(Status!=TaskStatus.InProgress)
throw new Exception("Can't finish what has not started");
Status=TaskStatus.Finished;
}
}
//value object
public enum TaskStatus{ Pending, InProgress, Finished }
var me=new User();
_users.Save(me);
var you=new User();
_users.Save(you);
var project=new Project(me);
project.RegisterTask("Have a nice day!", you);
project.StartWorkOn(project.Tasks.First());
_projects.Save(project);
请记住 - 这只是一个草图。不要太认真。