我有一个Person类和两个名为Parent和Child的继承类.父母可以有n个孩子,孩子可以有n个父母.
OOD在父和子之间创建引用的最佳方法是什么.
我应该在引用连接的父/子的每个类中创建一个List,还是有更好的方法?
Ian*_*son 11
好问题.纯粹的多对多关系实际上非常罕见,它通常有助于引入一个中间对象来模拟关系本身.如果(当!)用例出现需要捕获关于关系的属性(例如,子/父关系是自然的,代理的,收养的等),这将是非常宝贵的.
因此,除了您已经识别的Person,Parent和Child实体之外,让我们引入一个名为ParentChildRelationship的对象.ParentChildRelationship的实例将只引用一个Parent和One Child,Parent和Child类都将包含这些实体的集合.
然后,最好确定使用这些实体的用例,并添加适当的辅助方法来维护对象间引用.在下面的示例中,我刚刚选择将公共AddChild方法添加到父级.
public abstract class Person
{
}
public class Parent : Person
{
private HashSet<ParentChildRelationship> _children =
new HashSet<ParentChildRelationship>();
public virtual IEnumerable<ParentChildRelationship> Children
{
get { return this._children; }
}
public virtual void AddChild(Child child, RelationshipKind relationshipKind)
{
var relationship = new ParentChildRelationship()
{
Parent = this,
Child = child,
RelationshipKind = relationshipKind
};
this._children.Add(relationship);
child.AddParent(relationship);
}
}
public class Child : Person
{
private HashSet<ParentChildRelationship> _parents =
new HashSet<ParentChildRelationship>();
public virtual IEnumerable<ParentChildRelationship> Parents
{
get { return this._parents; }
}
internal virtual void AddParent(ParentChildRelationship relationship)
{
this._parents.Add(relationship);
}
}
public class ParentChildRelationship
{
public virtual Parent Parent { get; protected internal set; }
public virtual Child Child { get; protected internal set; }
public virtual RelationshipKind RelationshipKind { get; set; }
}
public enum RelationshipKind
{
Unknown,
Natural,
Adoptive,
Surrogate,
StepParent
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4460 次 |
最近记录: |