实战if-else 过多详解
1.本文实例代码仅仅是俩个小例子。
package com.example.demo.pattern.ifElse; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Function; /** * 如何解决解决类似 * 1 if (condition1) { * 2 * 3 } else if (condition2) { * 4 * 5 } else if (condition3) { * 6 * 7 } else if (condition4) { * 8 * 9 } else { * 10 * 11 } * * 1 if (param.equals(value1)) { * 2 doAction1(someParams); * 3 } else if (param.equals(value2)) { * 4 doAction2(someParams); * 5 } else if (param.equals(value3)) { * 6 doAction3(someParams); * 7 } * 8 */ public class SolveIfElseOne { //定义结构 属于工厂模式 private static final Map<String, Consumer<String>> map=new HashMap<>(); private static final Map<Integer, Function<Integer,Double>> map1=new LinkedHashMap<>(); //初始化数据 static{ map.put("1",(param)->{doAction1(param);}); map.put("2",(param)->{doAction2(param);}); map.put("3",(param)->{doAction3(param);}); map1.put(2200,(param)->{return doAction2200(param);}); map1.put(2700,(param)->{return doAction2700(param);}); map1.put(3200,(param)->{return doAction3200(param);}); } /** * 未重构前 */ public void handle(String param){ if (param.equals("1")) { doAction1(param); } else if (param.equals("2")) { doAction2(param); } else if (param.equals("3")) { doAction3(param); } } public static void doAction1(String param){ System.out.println(param); } public static void doAction2(String param){ System.out.println(param); } public static void doAction3(String param){ System.out.println(param); } public static double doAction2200(int income){ double tax = 0; return tax = 0; } public static double doAction2700(int income){ double tax = tax = 0.14 * (income - 2200); return tax ; } public static double doAction3200(int income){ double tax = 70 + 0.15 * (income - 2700); return tax; } public static double getTax(int income){ double res=0; for(Integer integer:map1.keySet()){ if(income<=integer) { System.out.println(integer+" "); res=map1.get(integer).apply(income); System.out.println(map1.get(integer).apply(income)+" "); break; } } return res; } public static void main(String[] args) { SolveIfElseOne.map.get("1").accept("1"); System.out.println(getTax(3200)); } }
版权声明:本文为love-htt原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。