多态性而非泛型的条件转换

时间:2018-11-03 21:20:07

标签: java oop generics polymorphism refactoring

我有一些代码。我发现了一些有关“在不使用if / else,switch / case或?运算符的情况下重构OOP代码中的代码的帖子。请帮助我将其与泛型一起使用。我花了太多时间,但暂时找不到解决方案。您能否给出OOP中重构素的构想?

public class Main {

    public static void main(String[] args) throws Exception {
        System.out.println("result is :"+function(6,4,0));
        System.out.println("result is :"+function(6,4,1));
        System.out.println("result is :"+function(6,4,2));
        System.out.println("result is :"+function(6,4,3));
        System.out.println("result is :"+function("6", "4", 0));
    }

    public static int function(int a, int b, int action) throws Exception
    {
        if (action == 0)
            return a+b;
        else if (action == 1)
            return a-b;
        else if (action == 2)
            return a*b;
        else if (action == 3)
            return a/b;
        throw new Exception();
    }

    public static String function(String a, String b, int action) throws Exception
    {
        if (action == 0)
            return a+b;
        throw new Exception();
    }

}

1 个答案:

答案 0 :(得分:0)

类似的东西:

interface BinaryOperation<T> {
    double evaluate(T operand1, T operand2);
}

class AddOperation<T> {
    private Function<T,Double> toDouble;
    public AddOperation(Function<T,Double> toDouble){this.toDouble=toDouble;}
    public double evaluate(T operand1, T operand2){ return toDouble.apply(operand1)  + toDouble.apply(operand2); }
}

class SubOperation<T> {
    private Function<T,Double> toDouble;
    public SubOperation (Function<T,Double> toDouble){this.toDouble=toDouble;}
    public double evaluate(T operand1, T operand2){ return toDouble.apply(operand1)  - toDouble.apply(operand2); }
}

public static void main(String[] args) {
    System.out.println("result is :" + new AddOperation<>(Integer::doubleValue).evaluate(6, 4));
    System.out.println("result is :" + new AddOperation<>(Double::parseDouble).evaluate("6", "4"));
}