假设我有一个应用程序,需要对字符串应用几个自定义转换。需求将随着时间的推移而增长。以下两种方法所做的事情完全相同,但我想知道哪一种方法从长远来看更有益处。是一样的吗?或者,随着转换次数的增加和变化,其中一个会比另一个提供更多的好处吗?
假设我们有这些:
public static final String PL = "(";
public static final String PR = ")";
public static final String Q1 = "'";以下是每种方法的设置和使用情况。
方法1:
@FunctionalInterface
public interface StringFunction {
String applyFunction(String s);
}
public class StrUtils {
public static String transform(String s, StringFunction f) {
return f.applyFunction(s);
}
public static String putInQ1(String s) {
return Q1.concat(s).concat(Q1);
}
public static String putInParens(String s) {
return PL.concat(s).concat(PR);
}
// and so on...
}我会这样用的:
System.out.println(StrUtils.transform("anSqlStr", StrUtils::putInQ1));
System.out.println(StrUtils.transform("sqlParams", StrUtils::putInParens));方法2:
在这里,我使用简单的函数:
Function<String, String> putInQ1 = n -> Q1.concat(n).concat(Q1);
Function<String, String> putInParens = n -> PL.concat(n).concat(PR);
// and so on...我会这样用的:
System.out.println(putInQ1.apply("anSqlStr");
System.out.println(putInParens.apply("sqlParams");发布于 2016-12-24 01:10:11
为什么不简单地定义方法‘putInWhatever(字符串s,字符串左,字符串右){返回左+s+右;}
在左和右相等的情况下,使用重载变体。不需要复杂的功能接口和lambda
https://stackoverflow.com/questions/41309081
复制相似问题