While reading effective java Chapter 5, Item 27
It talks about generic singleton pattern :
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));
}
}
}
I can't understand what does apply
method actually do!
It's like getting an object and returning itself. why? some useless sample?
Would someone tell me the use case please ?