我有一个输入文件(text => TextFileImporter
或xml => XmlFileImporter
),其中包含具有不同结构的数据。 Definiton
类中描述了一个结构,因此我的FileImporter
对象包含Definition
的多个实例。
TextFileImporter
应保留List<TextDefinition>
而XmlFileImporter
应保留List<XmlDefinition>
。
请查看示例代码:
// Parent classes
abstract class Definition {}
abstract class FileImporter {
protected List<Definition> definitions;
public FileImporter(List<Definition> definitions) {
this.definitions = definitions;
}
public void doSomething() {
// use 'definitions'
}
}
// Text files
class TextDefinition extends Definition {
public void copyLine() {}
}
class TextFileImporter extends FileImporter {
// here should be clear that 'definitions' is of type List<TextDefinition>
// to call 'copyLine()' on its items
}
// XML files
class XmlDefinition extends Definition {
public void copyNode() {}
}
class XmlFileImporter extends FileImporter {
// here should be clear that 'definitions' is of type List<XmlDefinition>
// to call 'copyNode()' on its items
}
正如您在评论的基础上所看到的,我不确定如何处理这个问题。当然我首先需要构造函数。然后,我不想每次只调用方法时将definitions
的每个项目转换为合适的子类。
我可以在这里合理使用仿制药吗?还是有另一种解决方案吗?
答案 0 :(得分:3)
你必须介绍一些泛型。
// Parent classes
abstract class Definition {}
abstract class FileImporter<T extends Definition> {
protected List<T> definitions;
public FileImporter(List<T> definitions) {
this.definitions = definitions;
}
public void doSomething() {
// use 'definitions'
}
}
// Text files
class TextDefinition extends Definition {
public void copyLine() {}
}
class TextFileImporter extends FileImporter<TextDefinition> {
// here should be clear that 'definitions' is of type List<TextDefinition>
// to call 'copyLine()' on its items
}
// XML files
class XmlDefinition extends Definition {
public void copyNode() {}
}
class XmlFileImporter extends FileImporter<XmlDefinition> {
// here should be clear that 'definitions' is of type List<XmlDefinition>
// to call 'copyNode()' on its items
}