前言
日常开发中或者代码优化过程中,一定会遇到不少的if语句,如果判断逻辑多了,会导致代码极其冗余,阅读性也会大打折扣,"消灭"if语句的方式有很多,也分不同的场景,本文将使用枚举策略的方式优化繁琐的if语句,你可以参考下文。
Example
package org.example.strategy;
import java.util.HashMap;
/**
* @author Duansg
* @date 2022-11-22 11:19 上午
*/
public class Example {
/**
*
* @param args
*/
public static void main(String[] args) {
final HashMap<String, Long> carsMap = new HashMap<String, Long>() {
{
put(CarContant.BMW, 100000L);
put(CarContant.BENZ, 88888L);
put(CarContant.AUDI, 77777L);
}
};
if (carsMap.containsKey(CarContant.BMW)) {
System.out.printf("这是一辆宝马, 价格:%s%n", carsMap.get(CarContant.BMW));
}
if (carsMap.containsKey(CarContant.BENZ)) {
System.out.printf("这是一辆奔驰, 价格:%s%n", carsMap.get(CarContant.BENZ));
}
if (carsMap.containsKey(CarContant.AUDI)) {
System.out.printf("这是一辆奥迪, 价格:%s%n", carsMap.get(CarContant.AUDI));
}
}
/**
*
*/
public static class CarContant {
public static final String BMW = "BMW";
public static final String BENZ = "BENZ";
public static final String AUDI = "AUDI";
}
}
StrategyExample
package org.example.strategy;
import java.util.Objects;
import java.util.stream.Stream;
/**
* @author Duansg
* @date 2022-11-22 11:24 上午
*/
public enum StrategyExample {
/**
*
* @param args
*/
public static void main(String[] args) {
final HashMap<String, Long> carsMap = new HashMap<String, Long>() {
{
put(CarContant.BMW, 100000L);
put(CarContant.BENZ, 88888L);
put(CarContant.AUDI, 77777L);
}
};
carsMap.forEach(StrategyExample::format);
}
/**
*
*/
BMW(Example.CarContant.BMW) {
@Override
public void print(Long price) {
System.err.printf("这是一辆宝马, 价格:%s%n", price);
}
},
BENZ(Example.CarContant.BENZ) {
@Override
public void print(Long price) {
System.err.printf("这是一辆奔驰, 价格:%s%n", price);
}
},
AUDI(Example.CarContant.AUDI) {
@Override
public void print(Long price) {
System.err.printf("这是一辆奥迪, 价格:%s%n", price);
}
};
/**
* 汽车名称
*/
private String carName;
/**
* 格式化方法
*
* @param carName
* @param price
*/
public static void format(String carName, Long price) {
if (Objects.isNull(carName)) {
return;
}
final StrategyExample strategyExample = Stream.of(StrategyExample.values())
.filter(strategy -> strategy.getCarName().equals(carName))
.findFirst()
.orElse(null);
if (Objects.isNull(strategyExample)) {
return;
}
strategyExample.print(price);
}
/**
* 打印方法
*
* @param price
*/
public abstract void print(Long price);
/**
*
* @param carName
*/
StrategyExample(String carName) {
this.carName = carName;
}
/**
*
* @return
*/
public String getCarName() {
return carName;
}
}