如果发现除了某些部分外,您的许多例程完全相同,那么您可能需要考虑使用Template Method来消除容易出错的代码重复 。 这是一个示例:下面是两个做类似事情的类:
- 实例化并初始化Reader以从CSV文件读取。
- 阅读每一行并将其分解为令牌。
- 将每行中的令牌解组到一个实体(产品或客户)中。
- 将每个实体添加到集合中。
- 返回集合。
正如您所看到的,只有在第三步中才有所不同–将编组到一个实体或另一个实体。 其他所有步骤均相同。 我已经突出显示了每个代码段中代码都不同的那一行。
ProductCsvReader.java
public class ProductCsvReader {
Set<Product> getAll(File file) throws IOException {
Set<Product> returnSet = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))){
String line = reader.readLine();
while (line != null && !line.trim().equals("")) {
String[] tokens = line.split("\\s*,\\s*");
Product product = new Product(Integer.parseInt(tokens[0]), tokens[1],
new BigDecimal(tokens[2]));
returnSet.add(product);
line = reader.readLine();
}
}
return returnSet;
}
}
CustomerCsvReader.java
public class CustomerCsvReader {
Set<Customer> getAll(File file) throws IOException {
Set<Customer> returnSet = new HashSet<>();
try (BufferedReader reader = new Buffered