【发布时间】:2009-11-02 15:53:00
【问题描述】:
我有许多在概念上都相关的类,但有些类在细节层面上比其他类更重要。例如,这三个类具有几乎相同的属性(尽管成员函数会有所不同):
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;
}
这可以在很多地方重复。有没有更好的设计方法我应该使用(一定有)?
【问题讨论】:
标签: c# design-patterns oop