代码之家  ›  专栏  ›  技术社区  ›  Bullines

创意设计/图案建议请求

  •  1
  • Bullines  · 技术社区  · 15 年前

    我有许多类,它们在概念上都是相关的,但在细节层面上,有些更是如此。例如,这三个类具有几乎相同的属性(尽管成员函数会有所不同):

    public class RelatedA : IRelatedType
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public DateTime Stamp { get; set; }
    }
    
    public class RelatedB : IRelatedType
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public DateTime Stamp { get; set; }
    }
    
    public class RelatedC : IRelatedType
    {
        public string Name { get; set; }
        public string Value { get; set; }
        public DateTime Stamp { get; set; }
        public int Special { get; set; }
    }
    

    还有两个其他类在概念上与上述3个类相关,但在实现方面可能略有不同:

    public class RelatedD : IRelatedType
    {
        public string Name { get; set; }
        public string Statement { get; set; }
    }
    
    public class RelatedE : IRelatedType
    {
        public string Name { get; set; }
        public string Statement { get; set; }
        public bool IsNew { get; set; }
    }
    

    这些实例可以由工厂基于某种“类型”枚举值创建。问题是,稍后在使用这些对象时(例如,在业务层中),可能会有很多这样的代码:

    IRelatedType theObject = TheFactory.CreateObject(SomeEnum.SomeValue);
    
    if (theObject is RelatedC)
    {
        RelatedC cObject = theObject as RelatedC;
        specialVal = cObject.Special;
    }
    else if (theObject is RelatedD)
    {
        RelatedD dObject = theObject as RelatedD;
        statementVal = dObject.Statement;
    }
    else if (theObject is RelatedE)
    {
        RelatedE eObject = theObject as RelatedE;
        statementVal = eObject.Statement;
        isNewVal = eObject.IsNew;
    }
    

    这可能在许多地方重复。是否有更好的设计方法,我应该使用(必须有)?

    1 回复  |  直到 15 年前
        1
  •  1
  •   JoshBerke    15 年前

    您可以尝试将差异分解为单独的类,然后提供这些类,例如:

    IRelatedType theObject = TheFactory.CreateObject(SomeEnum.SomeValue);
    RelatedTypeHelper theHelper=TheFactory.CreateHelper(theObject);
    theHelper.DoSpecialThing(theObject);
    

    我还想问,为什么一个方法会对specialVal和StatementVal有如此不同的实现,而StatementVal可能是您的示例,但这让我好奇您到底在这里做什么。你能把事情简化回去吗?退一步,质疑这些东西是否包含在这个特定的层次结构中。