General Singleton Factory

While reading on the Internet, I came across the following:

public interface UnaryFunction<T>
{
    T apply(T arg);
}

.......


private static UnaryFuntion<Object> ID_FUNC = new UnaryFunction<Object>
                                          {
                                             Object apply(Object arg)
                                             {
                                                  return arg;
                                             }
                                          };

public static <T> UnaryFunction<T> idFunction()
{
    return (UnaryFunction<T>) ID_FUNC;
}

In main:

public static void main(String[] args)
{
    String[] strings = {"Peter", "Paul", "Mary"};
    UnaryFunction<String> names = idFunction();
    for(String s : strings)
    {
        System.out.println(names.apply(s));
    }

    Number[] numbers = {1, 2.0, 3L};
    UnaryFunction<Number> nums = idFunction();
    for(Number n : numbers)
    {
        System.out.println(nums.apply(n));
    }
}

My question is: why do we need a common here interface?

It would be enough:

public interface UnaryFunction
{
    Object apply(Object arg); //Object as return type and argument type, instead.
}

? What is the need for generics here?

And, what is actually a common factory single? What is this good for?

Thank.

+4
source share
1 answer

The general singleton factory is idFunction in your example. Without this, you will have a choice between two ugly alternatives, or you need a throw where you use it, for example:

public class ExampleWithoutGenericSingletonFactory {

    static UnaryFunction<Object> ID_FUNC = new UnaryFunction<Object>() {
        public Object apply(Object arg) {
            return arg;
        }
    };

    public static void main(String[] args) {
        BigDecimal b = new BigDecimal("1234.1241234");
        BigDecimal b1 = (BigDecimal)(ID_FUNC.apply(b)); // have to cast here >_<
        System.out.println("engineeringstring val of b1 = " 
        + b1.toEngineeringString());
    }
}

or make separate implementations for each type that you want to support:

public static UnaryFunction<String> ID_FUNC_STRING = new UnaryFunction<String>() {
    public String apply(String arg) {
        return arg;
    }
};

public static UnaryFunction<Number> ID_FUNC_NUM = new UnaryFunction<Number>() {
    public Number apply(Number arg) {
        return arg;
    }
};

public static UnaryFunction<BigDecimal> ID_FUNC_DECIMAL = new UnaryFunction<BigDecimal>() {
    public Number apply(BigDecimal arg) {
        return arg;
    }
};

, . , , , (ID_FUNC) idfunction singleton factory.

, , , .

, toString , , factory. , .

, , ( , ).

+2

Source: https://habr.com/ru/post/1542554/


All Articles