public class ReportBuilder {
private final DataParser parser = new DataParser();
private final DataReader reader = new DataReader();
private List<ReportRecord> recordList;
enum EndOrStart {
END, START
}
public List<String> prepareReport(String startFile, String endFile, String abbrevFile) {
formatChart(abbrevFile);
addTime(startFile, EndOrStart.START);
addTime(endFile, EndOrStart.END);
recordList.forEach(rec -> rec.setTimeDiff(rec.getEndTime().toNanoOfDay()-rec.getStartTime().toNanoOfDay()));
sortByDiffTime();
return collectReport();
}
private Stream<String> recordToString(int index) {
String timeFormat = "m:ss.SSS";
String reportFormat = "%d. %s | %s | %s";
String delimiter = "-".repeat(60);
ReportRecord dataRecord = recordList.get(index);
String name = dataRecord.getName();
String team = dataRecord.getTeam();
String time = LocalTime.ofNanoOfDay(dataRecord.getTimeDiff()).format(DateTimeFormatter.ofPattern(timeFormat));
String result = String.format(reportFormat, 1 + index, name, team, time);
return (1 + index) % 15 == 0
? Stream.of(result, delimiter)
: Stream.of(result);
}
private ArrayList<String> collectReport() {
return IntStream.range(0, recordList.size())
.mapToObj(this::recordToString)
.flatMap(s -> s)
.collect(Collectors.toCollection(ArrayList::new));
}
private void formatChart(String abbrevFile) {
List<String> abbrevList = reader.readFile(abbrevFile);
recordList = new ArrayList<>(abbrevList.size());
abbrevList.stream().sorted(Comparator.naturalOrder())
.forEach(line -> recordList.add(parser.parseRacer(line)));
}
private void addTime(String timeFile, EndOrStart startOrEndFile) {
List<String> timeStringList = reader.readFile(timeFile);
timeStringList.sort(Comparator.naturalOrder());
List<LocalTime> timeList = timeStringList.stream().map(parser::parseTime).collect(Collectors.toList());
if (startOrEndFile.equals(EndOrStart.START)) {
recordList.forEach(rec -> rec.setStartTime(timeList.get(recordList.indexOf(rec))));
}
if (startOrEndFile.equals(EndOrStart.END)) {
recordList.forEach(rec -> rec.setEndTime(timeList.get(recordList.indexOf(rec))));
}
}
在 addTime 方法中,我将有关开始时间 (startTime) 和结束时间 (entTime) 的数据添加到 ReportRecord 类的实例中。为了使 addTime 方法具有通用性,我在 prepareReport 方法中调用了两次,并将其作为第二个枚举参数传递,该参数指示我正在为哪个字段赋值。我们如何摆脱枚举类并保持 addTime 方法的通用性?
在最简单的情况下,您可以将 enum 替换为 true/false 标志。一个更美观、更通用的选择是将行为逻辑作为参数传递给方法。
好吧,挑战: