我正在阅读 Effective Java。在讨论使用函数对象作为策略的部分中,存在以下段落。
Because the strategy interface serves as a type for all of its concrete strategy instances, a concrete strategy class needn’t be made public to export a concrete strategy. Instead, a “host class” can export a public static field (or static factory method) whose type is the strategy interface, and the concrete strategy class can be a private nested class of the host
// Exporting a concrete strategy
class Host {
private static class StrLenCmp
implements Comparator<String>, Serializable {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
// Returned comparator is serializable
public static final Comparator<String>
STRING_LENGTH_COMPARATOR = new StrLenCmp();
... // Bulk of class omitted
}
我的问题是,使用上述方式有什么特别的优势吗?通过公开具体策略来导出策略有什么问题?
最佳答案
是的,有。这样你返回的是接口(interface)而不是具体类,所以如果你更改 Comparator 接口(interface)的具体实现,你不必也修改客户端类(我认为这是使用接口(interface)的最重要原因)。
例如:
//inside aClass
Comparator c = Host.STRING_LENGTH_COMPARATOR; //Programming against interfaces is different from:
StrLenCmp c = Host.STRING_LENGTH_COMPARATOR; //programming against concrete class
假设将来您将使用另一个实现(我们称之为 NewStrLenCmp)更改 StrLenCmp,而不是如果您针对接口(interface) Comparator 进行编程则不必修改 aClass。
Comparator c = Host.STRING_LENGTH_COMPARATOR; //still work because interface doesn't changed
NewStrLenCmp c = Host.STRING_LENGTH_COMPARATOR; // problem: you need to modify the client class in order to use the new concrete type: bad idea
关于java : Function objects as strategies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7993275/