Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Java模拟函数模板_Java_Generics_Function Template - Fatal编程技术网

用Java模拟函数模板

用Java模拟函数模板,java,generics,function-template,Java,Generics,Function Template,我正在尝试模拟类似于Java中函数模板的东西,从某种意义上说,我有如下类似的东西: public interface MyFunctionTemplate<T> { void doSomething(T thing); } public class MyIntegerFunctionTemplate extends MyFunctionTemplate<Integer> { ... } public class MyStringFunctionTemplate

我正在尝试模拟类似于Java中函数模板的东西,从某种意义上说,我有如下类似的东西:

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

public class MyIntegerFunctionTemplate extends MyFunctionTemplate<Integer> { ... }
public class MyStringFunctionTemplate extends MyFunctionTemplate<String> { ... }
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);
}
公共接口MyFunctionTemplate{
无效物质(T物质);
}
公共类MyIntegerFunctionTemplate扩展了MyFunctionTemplate{…}
公共类MyStringFunctionTemplate扩展MyFunctionTemplate{…}
看来我需要某种类型的中央注册表。如下所示:

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

public class MyIntegerFunctionTemplate extends MyFunctionTemplate<Integer> { ... }
public class MyStringFunctionTemplate extends MyFunctionTemplate<String> { ... }
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);
}
公共类MyFunctionTemplateRegistry{
私有静态映射>注册表;
公共静态无效寄存器(类templateClass、MyFunctionTemplate templateFunction);
公共静态无效物(客体物);
}

设计这种东西的最佳方法是什么?

好吧,这取决于您想要实现什么,以及实现类是否需要知道类型。对我来说,你的建议似乎设计过度(太复杂),但如果没有更具体的信息,真的很难说

我这么说的原因是,我不喜欢为接口实现两个单独的类(每种类型一个)。使用泛型的优势通常在于找到一种方法,用一个使用泛型类型T的类来实现它

再说一次,我可能误解了你的意图

无论如何,作为一个简单的例子,如果你的函数是纯数学的,比如
getMax()
getMin()
,那么你肯定不需要知道更多关于t的事情,只需要知道t与t是可比的

然后你可能会得到这样的结果:

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;
    }
}
公共类FindExtremes{
T getMax(T a,T b){
返回a.compareTo(b)>=0?a:b;
}
T getMin(T a,T b){

返回a.compareTo(b)你刚刚做了,有什么问题吗?