背景:
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 = 3;
int newDate = 7;
Map> dates = throughMonth();
for (Integer key :dates.keySet()) {
if (key < date) {
continue;
}
System.out.println("i: " + key);
dates.get(key).apply(newDate);
}
}
private static Map> throughMonth() {
Map> dates = new linkedHashMap<>(); // 使用排序的哈希算法
dates.put(MONTH_5, throughMonth5);
dates.put(MONTH_6, throughMonth6);
dates.put(MONTH_7, throughMonth7);
return dates;
}
private static final Function throughMonth5 = (Integer date) -> {
System.out.println("走过了5月份:" + date);
return null;
};
private static final Function throughMonth6 = (Integer date) -> {
System.out.println("走过了6月份:" + date);
return null;
};
private static final Function throughMonth7 = (Integer date) -> {
System.out.println("走过了7月份:" + date);
return null;
};
}



