签名,有几个选项(大致类似于您的示例,但此模式可推广)。
第一个选项可能是:
/**
* Computes ... something, and returns the result as a map
*/
Map<Date, Result> execute(Date d0, Date d1) { ... }
第二个可能是:
void execute(Date d0, Date d1, Map<Date, Result> results) { ... }
然而,为了最大限度的灵活性,我经常参考第三个选项(也就是你实际询问的那一个):
Map<Date, Result> execute(
Date d0, Date d1, Map<Date, Result> results) { ... }
这有几个优点:
You conveniently let the call create a new map:
Map<Date, Result> results = execute(d0, d1, null);
You can determine the implementation of the target data structure. If you always returned a new map, then there would be no way to choose between a HashMap
or a LinkedHashMap
, for example. Passing the target data structure to the method allows you to call
Map<Date, Result> results =
execute(d0, d1, new HashMap<Date, Result>());
or
Map<Date, Result> results =
execute(d0, d1, new LinkedHashMap<Date, Result>());
respectively
You don't have to create a new map for each call. For example, you could create a sequence of calls
Map<Date, Result> results = new HashMap<Date, Result>();
execute(d0, d1, results);
execute(d2, d3, results);
accumulating the results in the given map
当考虑到这种方法可以轻松地模拟两种替代方案时,它的强大之处可能会变得更加明显:
class DB {
private Map<Date, Result> executeImpl(
Date d0, Date d1, Map<Date, Result> results);
public Map<Date, Result> execute(Date d0, Date d1) {
return executeImpl(d0, d1, null);
}
public void execute(Date d0, Date d1, Map<Date, Result> results) {
executeImpl(d0, d1, results);
}
}
一个旁注:Java SDK 的某些地方也使用了类似的模式。例如,在另一个应用案例中:BufferedImageOp#filter:
BufferedImage filter(BufferedImage src, BufferedImage dest)
... 如果目标图像为 null,则创建具有适当 ColorModel 的 BufferedImage。
返回:过滤后的 BufferedImage
HashMap
是完全不必要的。 - meskobalazs