2

I'm trying to simulate something analogous to a function template in Java, in the sense that I have something like the following:

public interface MyFunctionTemplate<T> {
    void doSomething(T thing);
}

public class MyIntegerFunctionTemplate extends MyFunctionTemplate<Integer> { ... }
public class MyStringFunctionTemplate extends MyFunctionTemplate<String> { ... }

It appears that I will need a central registry of some sort. Something like the following:

public class MyFunctionTemplateRegistry {
    private static Map<Class<?>, MyFunctionTemplate<?>> registry;

    public static <T> void register(Class<T> templateClass, MyFunctionTemplate<T> templateFunction);

    public static void doSomething(Object thing);
}

What is the best way to design such a thing?

Kelvin Chung
  • 1,327
  • 1
  • 11
  • 23

1 Answers1

0

Well, it depends on what you want to achieve and whether the implementing class needs to know the type or not. To me, your suggestion seems overdesigned (too complex), but it is really hard to say without having more concrete information.

The reason I'm saying this, is that I don't like the fact that you want to implement two separate classes for your interface (one for each type). The strength of using generics is often in finding a way to implement it with one class using the generic type T.

Then again, I might have misunderstood your intentions here...

Anyway, as a simple example, if your function(s) are purely mathematical, something like getMax() and getMin(), then you surely don't need to know anything more about T than the fact that T is comparable with T.

Then you could end up with something like this:

public class FindExtremes<T extends Comparable<T>> {
    T getMax(T a, T b) {
        return a.compareTo(b) >= 0 ? a : b;
    }
    T getMin(T a, T b) {
        return a.compareTo(b) <= 0 ? a : b;
    }
}

This could the be used directly for any class that implements Comparable, e.g.

new FindExtremes<Integer>().getMax(4, 5);
new FindExtremes<Double>().getMax(4.444D, 5.555D);
new FindExtremes<String>().getMax("abc", "zyx");
Steinar
  • 5,860
  • 1
  • 25
  • 23