During the module OGP you created your own CSVReader in week 3. The responsibility for that class is providing you with methods that read the content of a file. Usually you want to use that content to create a list of specific objects.
Let’s see what we can do with generics.
classDiagram
class Creator~T~ {
T create(data:String[]);
}
<<interface>> Creator
class LambdaReader~T~ {
-???
+ObjectReader(filename:String, creator:Creator~T~);
+readObjects(): ArrayList~T~
}
<<final>> LambdaReader
Creator~T~ <-- LambdaReader
class PersonCreator {
Person create(data: String[]);
}
Creator <|-- PersonCreator
Person <--o PersonCreator
And you even get a piece of code for free:
public final class LambdaReader<T> extends CSVReader {
public LambdaReader(String filename, Creator<T> creator){}
public ArrayList<T> readObjects() {
ArrayList<T> result = new ArrayList<>();
while (readLine()) {
T temp = creator.create(getColumns());
result.add(temp);
}
return result;
}
}
This ObjectReader
can be final because the Creator
interface will
handle all conversions to the type that we don’t know about.
Assignment
CSVReader
class.
Creator
for processing data to Persons.Creator
for processing data to Food and drinks.