Domain Driven Design - Parent child relation pattern - Specification pattern

前端 未结 3 723
清酒与你
清酒与你 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:59

    Since I've just encountered the same design desissions and question still not marked as answered I'll post my vision on solution of this problem - maybe it'll help anyone. This solution actually perfectly viable for use with NHibernate.

    public class Parent
    {
        private readonly ISet _children = new HashedSet ();
        public virtual IEnumerable Children { get { return new ImmutableSet (this._children); }  }
    
    
        protected internal virtual void AddChild (Child child)
        {
            this._children.Add(child);
        }
    }
    
    
    public class Child
    {
        public virtual Parent Parent { get; protected set; }
    
    
        protected Child()
        {
        }
    
    
        public static Create (Parent parent)
        {
            if (parent == null)
                throw new ArgumentNullException ("parent");
    
            var child = new Child
            {
                Parent = parent
            };
    
            child.Parent.AddChild (child);
    
            return child;
        }
    }
    

    That's differs from your #2 option in a way that creation of the child object (and invalidating it's initial values) are gathered withing child object itself and not in parent object as you suggested in #2.

    Tho one thing I'm not sure if it's considered bad design or not if we create child objects with personal factory method (Child.Create).

    I hope someone with more experience in using DDD could comment on that.

提交回复
热议问题