1.使用枚举定义常量,减少魔法值:
@Getter
@AllArgsConstructor
public enum StatusEnum {
SUCCESS("01", "成功"),
FAIL("02", "失败");
private final String code;
private final String desc;
}
@Service
public class TestService implements ITestService {
@Override
public void test() {
//可读性和维护性相比于硬编码方式来说更好
Test.builder().status(StatusEnum.SUCCESS.getCode()).build();
Test.builder().status("01").build();
}
}
2.用于字段值映射
@Getter
@AllArgsConstructor
public enum KunEnum {
ONE("1", "鸡"),
TWO("2", "泥"),
THREE("3", "胎"),
FOUR("4", "美"),
FIVE("5", "你"),
SIX("6", "干"),
SEVEN("7", "嘛");
private final String code;
private final String name;
private static final Map<String, String> map;
static {
map = new HashMap<>(KunEnum.values().length);
for (KunEnum value : KunEnum.values()) {
map.put(value.getCode(), value.getName());
}
}
public static String getNameByCode(String code) {
String name = map.get(code);
if (StringUtils.hasText(name)) {
return name;
}
throw new RuntimeException("找不到对应的映射字段!");
}
}
@Service
public class TestService implements ITestService {
@Override
public void test() {
//传参code为3
String code = "3";
String name = KunEnum.getNameByCode(code);
//name值为"胎"
System.out.println(name);
}
}
3.根据不同的编码,统计不同的数据,例如根据不同颜色有对应的不同状态几种状态,拿到这几个状态去处理相对应的事件
@Getter
@AllArgsConstructor
public enum ColorEnum {
YELLOW("yellow", Arrays.asList("1", "2", "3")),
GREEN("green", Arrays.asList("4", "5", "6")),
RED("red", Arrays.asList("7", "8", "9"));
private final String color;
private final List<String> status;
public static List<String> getStatusByColor(String color) {
for (ColorEnum colorEnum : ColorEnum.values()) {
if (Objects.equals(colorEnum.getColor(), color)) {
return colorEnum.getStatus();
}
}
return Collections.emptyList();
}
}
@Service
public class TestService implements ITestService {
@Override
public void test() {
//传参code为green
String color = "green";
List<String> list = ColorEnum.getStatusByColor(color);
//执行相应处理
handleStatus(list, color);
}
}
4.枚举工厂,根据不同的参数类型去执行不同的业务逻辑
@Getter
@AllArgsConstructor
public enum LanguageEnum {
JAVA("java", "java语言", JavaServiceImpl.class),
PYTHON("python", "python语言", PythonServiceImpl.class),
GO("go", "go语言", GoServiceImpl.class);
private final String type;
private final String desc;
private final Class<?> service;
private static final Map<String, Class<?>> serviceMap;
static {
serviceMap = new HashMap<>(LanguageEnum.values().length);
for (LanguageEnum value : LanguageEnum.values()) {
serviceMap.put(value.getType(), value.getService());
}
}
public static ILanguageService getServiceByType(String type) {
Class<?> clazz = serviceMap.get(type);
if (Objects.nonNull(clazz)) {
return (ILanguageService) SpringContextUtils.getBean(clazz);
}
throw new RuntimeException("没找到");
}
}
public interface ILanguageService {
void getResult();
}
@Service
public class JavaServiceImpl implements ILanguageService {
@Override
public void getResult() {
System.out.println("java");
}
}
@Service
public class PythonServiceImpl implements ILanguageService {
@Override
public void getResult() {
System.out.println("python");
}
}
@Service
public class GoServiceImpl implements ILanguageService {
@Override
public void getResult() {
System.out.println("go");
}
}
@Component
public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (Objects.isNull(SpringContextUtils.applicationContext)) {
SpringContextUtils.applicationContext = applicationContext;
}
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
@Service
public class TestService implements ITestService {
@Override
public void test() {
String type = "java";
ILanguageService service = LanguageEnum.getServiceByType(type);
service.getResult();
}
}
5.枚举回调-判断订单是否逾期
@FunctionalInterface
public interface OrderFunction {
boolean judgeTime(Order order);
}
@AllArgsConstructor
@Getter
public enum OrderTimeEnum {
PAY("pay", "逾期打款", order -> LocalDateTime.now().isAfter(order.getPayTime())),
ARRIVAL("arrival", "逾期到货", order -> LocalDateTime.now().isAfter(order.getArrivalTime())),
END("end", "逾期完结", order -> LocalDateTime.now().isAfter(order.getEndTime()));
private final String code;
private final String desc;
private final OrderFunction function;
public static Boolean isOverdue(String code, Order order) {
for (OrderTimeEnum value : OrderTimeEnum.values()) {
if (Objects.equals(value.getCode(), code)) {
return value.getFunction().judgeTime(order);
}
}
throw new RuntimeException("找不到");
}
}
@RestController
@RequestMapping("/test")
public class Test {
@GetMapping("/overdue")
public Boolean test(@RequestParam String type) {
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Order order = Order.builder().arrivalTime(LocalDateTime.parse("2023-03-15 12:00:00", df))
.endTime(LocalDateTime.parse("2023-03-12 12:00:00", df))
.payTime(LocalDateTime.parse("2023-03-10 12:00:00", df))
.build();
return OrderTimeEnum.isOverdue(type, order);
}
private static void handleStatus(List<String> list, String color) {
}
}