问题:有多个方法含有以下类似的重复代码,以后可能会需要更多返回不同类型的方法。通过什么方式可以避免代码重复,任何方式都可以。某些设计模式可行吗?
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;
});
}