1.这种用到了stream,有点秀操作的感觉
@AllArgsConstructor
@Getter
public enum MessageTypeEnum {
TEXT(1, "正常"),
RECALL(2, "撤回消息"),
;
private final Integer type;
private final String desc;
private static Map<Integer, MessageTypeEnum> cache;
static {
cache = Arrays.stream(MessageTypeEnum.values()).collect(Collectors.toMap(MessageTypeEnum::getType, Function.identity()));
}
public static MessageTypeEnum of(Integer type) {
return cache.get(type);
}
}
2.普通写法
@Getter
@AllArgsConstructor
public enum SearchModeEnum {
/**
* mysql
*/
MYSQL("mysql", "mySqlSearchStrategyImpl"),
/**
* elasticsearch
*/
ELASTICSEARCH("elasticsearch", "esSearchStrategyImpl");
/**
* 模式
*/
private final String mode;
/**
* 策略
*/
private final String strategy;
/**
* 获取策略
*
* @param mode 模式
* @return {@link String} 搜索策略
*/
public static String getStrategy(String mode) {
for (SearchModeEnum value : SearchModeEnum.values()) {
if (value.getMode().equals(mode)) {
return value.getStrategy();
}
}
return null;
}
}
3.chatgpt优化的写法
使用静态代码块替代流操作初始化缓存:虽然使用流操作和Collectors.toMap()方法可以方便地初始化缓存,但在这个特定的情况下,使用静态代码块可能更简洁和高效。静态代码块在类加载时执行,并且只会执行一次。因此,可以将初始化缓存的逻辑放入静态代码块中,而无需在每次调用of()方法时重新计算缓存。以下是优化后的代码示例:
@AllArgsConstructor
@Getter
public enum MessageTypeEnum {
TEXT(1, "正常"),
RECALL(2, "撤回消息"),
;
private final Integer type;
private final String desc;
private static final Map<Integer, MessageTypeEnum> cache;
static {
cache = new HashMap<>();
for (MessageTypeEnum messageType : MessageTypeEnum.values()) {
cache.put(messageType.getType(), messageType);
}
}
public static MessageTypeEnum of(Integer type) {
return cache.get(type);
}
}