- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!