且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

领域驱动设计 - 父母子女关系模式 - 规范模式

更新时间:2022-01-29 01:02:39

我绝对喜欢建议2号,但我认为它忽略一些重要的事情是在3个发现,即如果一个孩子对象不能没有应采取在其构造对象存在。此外,孩子类的属性应为只读。 所以,你最终会是这样的:

I definitely like suggestion number 2, but I think that it misses something important that is found in 3, namely that if a Child object cannot exist without a Parent it should take a Parent object in its constructor. Furthermore the Parent property on the Child class should be read only. So you would end up with something like:

public class Parent 
{ 
    private ICollection<Child> children; 

    public ReadOnlyCollection Children { get; } 

    public Child CreateChild() 
    { 
        var child = new Child(this); 
        children.Add(child); 
        return child; 
    } 
} 


public class Child 
{ 
    internal Parent Parent 
    { 
       get; 
       private set; 
    } 

    internal Child(Parent parent) 
    { 
       this.Parent = parent;
    } 
}