Domain Driven Design - Parent child relation pattern - Specification pattern

前端 未结 3 733
清酒与你
清酒与你 2021-01-02 19:23

I was wondering which of the following is considered to be a best practice when dealing with parent child relationships.

1) The following example seems to be a commo

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-02 19:42

    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 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;
        } 
    } 
    

提交回复
热议问题