【发布时间】:2017-05-12 17:52:50
【问题描述】:
我正在编写一些 java 代码,但我不确定应该使用什么结构。我有不同的类,每个类都包含一个从文本文件接收一行文本的填充方法。文本文件的内容特定于类。我需要修改方法(如下所示),以便它读取特定的文本文件,然后用文本文件中的数据填充正确的类(对象)。读取文本文件(如下所示)的方法是相同的,无论它将填充的未知对象是什么,除了对象类型。
Public Class ReceivesMyTextFile{
/*This class receives my text file and does some other stuff. */
/*Common method. I do not want to put this readData method, which is
the same except one line of code, into each of my UnknownUntilRunTime
classes. */
public void readData(File inFile){
/* the contents of inFile determine which UnknownUntilRunTime class
to instantiate, and then call its populate method in the loop. */
/* I do not want to instantiate this object in the loop, but I can't
do it here either because I don't know what type it is yet. */
UnknownUntilRunTime unknownObject = new UnknownUntilRunTime();
//TextFileReader handles reading one line of text at a time using
//BufferedReader class.
TextFileReader tfr = new TextFileReader(inFile.getPath());
String currentRecord = tfr.getNextLine();
while(tfr.hasData()){
currentRecord = currentRecord.trim();
//This is the problem. I don't know this object until run-time
//The contents of inFile determines the object type.
//this is the only line of code different.
unknownObject.populate(currentLine);
currentRecord = tfr.getNextLine();
}
}
}
Public Class UnknownUntilRunTime{
/* this class represents one of many different types of products.
this class is unknown until the contents of the correlating text file
are read. */
public void populate(String currentLine){
//populate this object with data from each currentLine of text.
}
}
我的问题是,在不知道对象类型的情况下,我应该如何组织我的代码来调用这个常用方法?也许我应该以不同的方式做到这一点?这是使用继承、接口或泛型的示例吗?我只是不确定如何进行。任何带有示例的建议将不胜感激!谢谢!
【问题讨论】:
-
感觉这里可以使用工厂模式或策略模式,但没有更多细节很难确定。
-
您还需要哪些其他详细信息?
-
几乎所有东西,我想。
-
你尝试过仿制药吗?
标签: java generics inheritance interface