实战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 {
//定义结构 属于工厂模式 基于java8 lambda
private static final Map<String, Consumer<String>> map=new HashMap<>();
//用LinkedHashMap 是为了保证有序性
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);
}

//未重构前
/* 1 if income <= 2200
2 tax = 0
3 else if income <= 2700
4 tax = 0.14 * (income - 2200)
5 else if income <= 3200
6 tax = 70 + 0.15 * (income - 2700)
7 else if income <= 3700
8 tax = 145 + 0.16 * (income - 3200)
9 ......
10 else
11 tax = 53090 + 0.7 * (income - 102200)*/



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

}

}
 

 

posted @ 2020-04-17 11:06  liuxw666  阅读(321)  评论(0编辑  收藏  举报