【发布时间】:2014-04-10 23:00:09
【问题描述】:
我找不到对某些情况不太具体的问题,所以我会尽量让这个问题非常笼统。
例如,我们需要一组文档的提取器基类。每个文档都有其特定的属性,但它们最终都是文档。所以我们想为所有这些提供通用的提取操作。
尽管它们都是文档,正如我所说,它们还是有些不同。有些可能有一些属性,但有些可能没有。
假设我们有Document 基抽象类,以及从它继承的FancyDocument 和NotSoFancyDocument 类。
FancyDocument 有一个 SectionA,NotSoFancyDocument 没有。
也就是说,您认为最好的实施方式是什么?这是两个选项:
- 基类上的空虚方法
基类上的空虚方法将允许程序员仅覆盖对不同类型文档有意义的方法。然后我们将在抽象基类上有一个默认行为,它将为方法返回 default,如下所示:
public abstract class Document
{
public virtual SectionA GetDocumentSectionA()
{
return default(SectionA);
}
}
public class FancyDocument : Document
{
public override SectionA GetDocumentSectionA()
{
// Specific implementation
}
}
public class NotSoFancyDocument : Document
{
// Does not implement method GetDocumentSectionA because it doesn't have a SectionA
}
- 具体空方法或具体方法抛出
NotImplementedException
由于NotSoFancyDocument 没有有SectionA,但其他有,我们可以只为其中的方法返回默认,或者我们可以抛出NotImplementedException。这将取决于程序是如何编写的以及其他一些事情。我们可以想出这样的东西:
//// Return the default value
public abstract class Document
{
public abstract SectionA GetDocumentSectionA();
}
public class FancyDocument : Document
{
public override SectionA GetDocumentSectionA()
{
// Specific implementation
}
}
public class NotSoFancyDocument : Document
{
public override SectionA GetDocumentSectionA()
{
return default(SectionA);
}
}
或
//// Throw an exception
public abstract class Document
{
public abstract SectionA GetDocumentSectionA();
}
public class FancyDocument : Document
{
public override SectionA GetDocumentSectionA()
{
// Specific implementation
}
}
public class NotSoFancyDocument : Document
{
public override SectionA GetDocumentSectionA()
{
throw new NotImplementedException("NotSoFancyDocument does not have a section A");
}
}
就个人而言,我确实认为抽象方法方法更好,因为它的意思是“嘿,我需要你能够将 SectionA 作为文档。我不在乎如何。”而虚拟方法的意思是“嘿,我这里确实有这个 SectionA。如果它对你来说不够好,请随意改变我获取它的方式。”。
我确实认为第一个是面向对象编程气味的标志。
您对此有何看法?
【问题讨论】:
-
我相信这个问题更适合programmers.stackexchange.com
-
@AaronPalmer 谢谢 Aaron,我看到它关门了。那我把它贴在程序员上。谢谢!
标签: c# oop inheritance abstract-class abstraction