我有这些实体


用户
任务-每个任务都必须分配一个用户
项目-可以将任务分配给项目,但这不是必需的,必须将用户分配为项目创建者
TaskStatus-每个任务必须分配一个状态


我设计了聚合根如下

聚集根


具有实体的用户:任务,任务状态
项目


我朝正确的方向前进吗?

最佳答案

是的,听起来很正确。这是我在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);


请记住-这只是一个草图。不要太当真。

关于domain-driven-design - 在这种情况下,聚合根是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4745789/

10-11 12:18