背景: if else 嵌套层数套多,导致复杂度过高,因此采用采用表驱动的方式进行优化,目前只知道这种方法。
public class ThroughDate {
private static final int MONTH_5 = 5;
private static final int MONTH_6 = 6;
private static final int MONTH_7 = 7;
public static void main(String[] args) {
int date = 4;
throughMonth(date);
}
private static void throughMonth(int date) {
if (date < MONTH_5) {
throughMonth5(date);
}
if (date < MONTH_6) {
throughMonth6(date);
}
if (date < MONTH_7) {
throughMonth7(date);
}
}
private static void throughMonth5(int date) {
System.out.println("走过了5月份:" + date);
}
private static void throughMonth6(int date) {
System.out.println("走过了6月份:" + date);
}
private static void throughMonth7(int date) {
System.out.println("走过了7月份:" + date);
}
}
该例子的典型应用是安卓的数据库升级。 优化方式如下:
public class ThroughDate2 {
private static final int MONTH_5 = 5;
private static final int MONTH_6 = 6;
private static final int MONTH_7 = 7;
public static void main(String[] args) {
int date = 1;
int newDate = 8;
Map<Integer, Function<Integer, Void>> dates = throughMonth();
for (int i = date + 1; i < date + 1 + dates.size(); i++) {
System.out.println("i: " + i);
dates.get(i).apply(newDate);
}
}
private static Map<Integer, Function<Integer, Void>> throughMonth() {
Map<Integer, Function<Integer, Void>> dates = new LinkedHashMap<>();
dates.put(MONTH_5, throughMonth5);
dates.put(MONTH_6, throughMonth6);
dates.put(MONTH_7, throughMonth7);
return dates;
}
private static final Function<Integer, Void> throughMonth5 = (Integer date) -> {
System.out.println("走过了5月份:" + date);
return null;
};
private static final Function<Integer, Void> throughMonth6 = (Integer date) -> {
System.out.println("走过了6月份:" + date);
return null;
};
private static final Function<Integer, Void> throughMonth7 = (Integer date) -> {
System.out.println("走过了7月份:" + date);
return null;
};
}
|