在《Effective Java Item 27》中,Bloch 提倡使用通用单例工厂“创建不可变但适用于许多不同类型的对象”。他的例子是:
interface UnaryFunction<T> {
T apply(T t);
}
public class Example {
private static UnaryFunction<Object> IDENTITY_FUNCTION = (k -> k);
// [snip] detailed explanation of why this is safe...
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction) IDENTITY_FUNCTION;
}
public static void main(String... args) {
String[] strings = { "jute", "hemp", "nylon" };
UnaryFunction<String> sameString = identityFunction();
for (String s : strings) {
System.out.println(sameString.apply(s));
}
}
}
以下是 OpenJDK 如何实现恒等功能:
@FunctionalInterface
interface UnaryOperator<T> extends Function<T, T> {
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
鉴于 Java 8 支持接口(interface)上的静态方法,通用单例工厂是否仍然有用例?
最佳答案
接口(interface)中的默认方法和通用单例工厂是相互独立的。
虽然通用单例工厂是一种实现技术,允许您通过应用我们对 Java 内部知识(具体来说,我们对类型删除的知识)在不同上下文中重用同一对象,但接口(interface)中的默认方法可以让您共享实现“水平”。
您可以通过在默认方法实现中使用通用单例工厂来组合这两种技术:
@FunctionalInterface
interface UnaryOperator<T> extends Function<T, T> {
static UnaryOperator<Object> IDENTITY_FUNCTION = (k -> k);
static <T> UnaryOperator<T> identity() {
return (UnaryOperator)IDENTITY_FUNCTION;
}
}
所以你的问题的答案是“不,静态接口(interface)方法不会取代通用单例工厂”。
关于java - 静态接口(interface)方法与通用单例工厂的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071871/