我有 6 个类,它们都是文档类型。所有文档类型都有相同的 8 个字段。有一个类只包含这 8 个字段。其余的类有更多的领域。其中一些类具有相同的字段(除了 8 个字段)。
例子:
类文档:字段 1 到 8
类表格:字段 1 到 8 以及字段 9 和 10
类 WorkInstruction:字段 1 到 8 以及字段 9 和 10
类过程:字段 1 到 10 和字段 11
希望这能说明我的观点。
我的问题是,实现这一点的最佳方法是什么?我应该创建一个或多个接口,还是应该使用抽象类?
谢谢
要么使 Document 成为 Form 等的基本类型,要么使表单具有额外的字段和对单独 Document 的引用(即使用组合而不是继承)。在这种情况下,继承听起来很可能是最好的选择,但这真的取决于你想用它做什么。您是否有适用于任何文档的代码,包括 Form、WorkInstruction 等?
编辑:例如,假设您有一个用户界面控件,它可以显示任何文档的公共部分 - 即常见的 8 个字段。那将需要一个 Document 的实例。您可能希望能够直接将 Form 或 WorkInstruction 传递给它 - 在这种情况下,最好从 Document. 或者,在呈现 Form 或 WorkInstruction 时,您可以创建一个单独传入文档部分的控件实例。即这之间的区别(在 C# 中 - 你没有指定你感兴趣的语言):
class Form : Document { ... }
// Later on
Controls.Add(new DocumentDisplay(form));
还有这个:
class Form
{
private Document Document { get; set; }
// Other stuff
}
// Later on
Controls.Add (new DocumentDisplay(form.Document));
在不了解您设计的其余部分的情况下,很难推荐其中一种。我通常更喜欢组合而不是继承,但这感觉更像是一种自然的继承情况。
The old school answer would be creating a class with the shared fields and inherit.
The trendy answer would be to create a class that has those fiends and have it as a member.
Inheriting creates more dependency between the classes, if you will every change the base, which is considered bad practice.
In a simple case it doesn't really make that much difference. But if you start adding behavior to those fields it may.
Too little information to give a definitive answer
If the only thing these objects share is data attributes... I'd use something like this.
class Document
{
List<Field> m_Fields;
public void AddField(Field f) {... }
public void AddFields(Field[] f) {... }
}
class DocumentFactory()
{
public static Document GetDocument()
{
Document d = new Document();
d.AddFields(GetDocumentFields()); // private helper .. returns fields 1-8
return d;
}
public static Document GetForm()
{
Document d = new Document();
AddDocumentFields(d);
d.AddField(FIELD_9);
d.AddField(FIELD_10);
}
// and so on..
}
Any code that works irrespective of type of document, goes into the Document class.
If in addition to this you have behavior that is specialized/based on specific object type, you'd need to grow an inheritance type-hierarchy (as Jon says.. it looks like a IS-A relationship from the names.)