为不同的参数和类型编写具有相同业务逻辑的方法的最佳方法?

时间:2018-02-09 11:19:49

标签: java spring

为不同的参数和类型编写具有相同业务逻辑的方法的最佳方法是什么?

示例:

我有以下方法:

void condition(int a)
{ 
    if (a in range of)
    {
        log something with a;
    } else {
        log something with a;
    }
}

这里我需要为不同的数据类型调用相同的方法,我还需要使用我们传递给此方法的字段的特定名称进行记录,例如:

condition(b);

应该在声明中记录b。

1 个答案:

答案 0 :(得分:1)

你正在寻找这样的东西吗? (由一位伟大的记录员进行游戏)

import java.util.function.Predicate;

public class Condition<T> {

    public void test(Predicate<T> predicate, T aValue, String logIf, String logElse) {
        System.out.println(predicate.test(aValue) ? logIf : logElse);
    }


    public static void main(String[] args) {

        Condition<Integer> conditionInteger = new Condition<>();
        conditionInteger.test( v ->  v < 10, 15, "Log If with an integer", "log else with an integer");

        Condition<String> conditionString = new Condition<>();
        conditionString.test( v -> v.length() < 10, "a great String", "Log If with a string", "log else with a string");
    }
} 
相关问题