栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java多if-else转换为表驱动优化

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java多if-else转换为表驱动优化

背景:
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;
    };
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/643316.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号