优雅写代码三原创
# 怎么更好的避免if else 语句?
# 实现 InitializingBean 接口
# 创建业务枚举
public enum BizTypeEnum {
PRODUCT(1, "商品"),
SHOP(2, "店铺"),
CONTENT(3, "内容");
private Integer type;
private String desc;
private BizTypeEnum(Integer type, String desc) {
this.type = type;
this.desc = desc;
}
public static BizTypeEnum indexOf(Integer type) {
BizTypeEnum[] var1 = values();
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
BizTypeEnum item = var1[var3];
if (item.getType().equals(type)) {
return item;
}
}
return null;
}
public Integer getType() {
return this.type;
}
public String getDesc() {
return this.desc;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 创建业务缓存
/**
* 关注写操作服务 关注
*/
private final Map<BizTypeEnum, Function<FollowCollectRequest, BaseResult>> FOLLOW_WRITE_FUNCTION_MAP = new HashMap<>();
1
2
3
4
2
3
4
# 重写 afterPropertiesSet
@Override
public void afterPropertiesSet() throws Exception {
this.FOLLOW_WRITE_FUNCTION_MAP.put(BizTypeEnum.PRODUCT, (request) -> this.followProductCollectWriteApi.follow(request));
this.FOLLOW_WRITE_FUNCTION_MAP.put(BizTypeEnum.SHOP, (request) -> this.followShopCollectWriteApi.follow(request));
this.UN_FOLLOW_WRITE_FUNCTION_MAP.put(BizTypeEnum.PRODUCT, (request) -> this.followShopCollectWriteApi.unfollow(request));
this.UN_FOLLOW_WRITE_FUNCTION_MAP.put(BizTypeEnum.SHOP, (request) -> this.followShopCollectWriteApi.unfollow(request));
}
1
2
3
4
5
6
7
2
3
4
5
6
7
# 使用
/**
* 获取结果
*/
private BaseResult getResult(FollowCollectRequest request) {
return this.FOLLOW_WRITE_FUNCTION_MAP.get(request.getBizType()).apply(request);
}
1
2
3
4
5
6
2
3
4
5
6
编辑 (opens new window)
上次更新: 2022/05/01, 19:42:49