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)); } }