3

我需要在我的实体中对组织层次结构进行建模。一个组织可以是总部、区域负责人、子区域、区域办事处。组织正在执行许多通用功能,但有几个特定的​​功能,例如只有区域可以执行任务 A。还有一些特定于区域的属性(数据)。

我使用组合而不使用继承对其进行建模,但现在我只以一个组织类结束,其中有很多引用,这些引用取决于组织的类型,可以有有效的引用,也可以为空。

对象组合是一种痛苦,现在我正在通过工厂处理。但现在我主要关心的是开发人员需要记住组织类型是什么以及属性是否对该组织有意义。

只是为了清楚我的意思。

    public class Organization : IKeyed<int> {
        public virtual int Id { get; protected set; }
        public virtual string Code { get; set; }
        public virtual OrganizationType orgType {get;set;}
        public virtual Organization Parent {get;set;}
        public virtual IList<Organization> Children {get;set;}

        public virtual typeA {get; set;} // only meaningful when organization type is 'Head office'

        public virtual typeB {get;set;}// only meaningful when 'Region'
        public virtual void AddChild(Organization org){...}
    ...

    }

我应该在这里使用继承吗?还是我在这里错过了一些技巧?

4

2 回答 2

6

在我看来,我建议您创建一个包含常见行为和字段的抽象基类。然后,您可以添加子类来扩展更具体的行为和/或属性。

public abstract class Organization : IKeyed<int> { 
    public virtual int Id { get; protected set; } 
    public virtual string Code { get; set; }

    // remove this property
    // public virtual OrganizationType orgType {get;set;} 
    public virtual Organization Parent {get;set;} 
    public virtual IList<Organization> Children {get;set;} 

    // move this property to sub-class
    // public virtual typeA {get; set;} // only meaningful when organization type is 'Head office' 

    // move this property to sub-class
    // public virtual typeB {get;set;}// only meaningful when 'Region'

    public virtual void AddChild(Organization org){...} 
    ... 

}

public class HeadOffice : Organization
{
    public virtual typeA { get; set; }
}

public class Region : Organization
{
    public virtual typeB { get; set;}
}

public class OtherOrganizationType : Organization
{
    // 
}
于 2012-10-15T06:47:42.940 回答
1

关于您的具体问题继承与组合:我一遍又一遍地听到的格言是“当对象 A 是对象 B 的一种类型时使用继承。当对象 A 由对象 B 组成时使用组合”。

在这种情况下,您不能说区域办事处是总公司的一种。你也不能说总公司是由地区办事处组成的。这告诉我对象不应该直接相关。相反,想想是什么让他们有资格执行常见任务。也许他们都可以 HireWorker 因为他们都是 HiringOrganizations,也许他们都可以 ReportSales 因为他们都是 SalesEntities。在这些情况下,您应该有一个 HiringOrginization 或 SalesEntity 超类,HeadOffice 和 RegionalOffice 都是它们的子类。

就 org 结构而言,可能值得考虑在单独的 OrgStructure 对象中维护该结构。您的 OrgStructure 对象将维护所有对象实例之间的关系,而不是在每个对象中具有 Parent 属性和 Child 属性。这提供了更多的灵活性,并消除了将关系维护到专用对象的责任。

于 2012-10-16T19:53:20.247 回答