在阅读 effective java 第 5 章第 27 条时
它谈论通用单例模式:
Now suppose that you want to provide an identity function. It would be wasteful to create a new one each time it’s required, as it’s stateless. If generics were reified, you would need one identity function per type, but since they’re erased you need only a generic singleton. Here’s how it looks:
public class GenericSingleton<T> {
private static UnaryFunction<Object> IDENTIFY_FUNCTION = new UnaryFunction<Object>() {
@Override
public Object apply(Object args) {
return args;
}
};
@SuppressWarnings("unchecked")
public static <T> UnaryFunction<T> identityFunction() {
return (UnaryFunction<T>) 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));
}
Number[] numbers = {1, 2.0, 3L};
UnaryFunction<Number> sameNumber = identityFunction();
for (Number n : numbers) {
System.out.println(sameNumber.apply(n));
}
}
}
我不明白 apply
方法实际上是做什么的!
这就像获取一个对象并返回它本身。为什么?一些无用的样本?
有人可以告诉我用例吗?
最佳答案
一个用例是 Collectors.toMap()
.
假设您有一个由唯一键标识的项目列表,并且您需要一个从该唯一键到对象本身的Map
。
Collectors.toMap()
需要两个函数:
- 从对象中提取 key
- 另一个从对象中提取值的
由于值应该是对象本身,因此您需要一个接受对象并返回相同对象的函数 - 这就是您的身份函数。
关于java - 身份方法做什么,通用单例java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095229/