問題:有多個方法含有以下類似的重複代碼,以後可能會需要更多傳回不同類型的方法。通過什麼方式可以避免代碼重複,任何方式都可以。某些設計模式可行嗎?
public static Date readDate(String dir, String fileName) {
Path path = Paths.get(dir, fileName);
try (BufferedReader br = Files.newBufferedReader(path)) {
String result = br.readLine();
return DateUtils.parseDate(result, "yyyy-MM-dd");
} catch (IOException e) {
log.error("read fail file: " + path);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static Integer readInteger(String dir, String fileName) {
Path path = Paths.get(dir, fileName);
try (BufferedReader br = Files.newBufferedReader(path)) {
String result = br.readLine();
return Integer.valueOf(result);
} catch (IOException e) {
log.error("read fail file: " + path);
}
return null;
}
Analysis process: Return method is different, the one is return DateUtils.paseDate(result,"yyyy-MM-dd"), the anther one is return Integer.valueOf(result).
So someOne want to use Template method, In here I will use Java8 function to handle it.
public static <T> T read(String dir, String fileName, Function<String, T> fun) {
Path path = Paths.get(dir, fileName);
try (BufferedReader br = Files.newBufferedReader(path)) {
String result = br.readLine();
return fun.apply(result);
} catch (IOException e) {
log.error("read fail file: " + path);
}
return null;
}
The following code is revoke method.
@Test
private void test() {
read("/d", "test.txt", Integer::valueOf);
read("/d", "test.txt", date -> {
try {
return DateUtils.parseDate(date, "yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
return null;
});
}