记录一下实战用的Java策略模式

前言

  • 策略模式是为了减少主业务逻辑else if的代码量。
  • 当我们用策略模式的时候,要把else if的关系用另一种方式体现出来,以后如果要增加else if的关系,只需要增加策略模式的对应关系就可以。
  • 优点: 可以减少主业务逻辑的代码量,便于维护

一、接口方式

1.1 接口定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
java复制代码public interface Adapter {
/**
* 方法1
*
* @param actModel 参数
*/
void method1(Object param);

/**
* 方法2
*
* @param param 参数
*/
void method2(Object param);
}

1.2 实现类继承接口并实现方法

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
38
39
40
41
42
43
44
45
46
47
48
49
java复制代码/**
* 实现类1
*/
@Service
public class AdapterImplOne implements Adapter {
/**
* 方法1
*
* @param actModel 参数
*/
public void method1(Object param) {
// AdapterImplOne方法1具体实现
// ...
}
/**
* 方法2
*
* @param actModel 参数
*/
public void method2(Object param) {
// AdapterImplOne方法2具体实现
// ...
}
}

/**
* 实现类2
*/
@service
public class AdapterImplTwo implements Adapter {
/**
* 方法1
*
* @param actModel 参数
*/
public void method1(Object param) {
// AdapterImplTwo方法1具体实现
// ...
}
/**
* 方法2
*
* @param actModel 参数
*/
public void method2(Object param) {
// AdapterImplOne方法2具体实现
// ...
}
}

1.3 找到不同实现类之间的对应关系

接口模式的对应关系,我一般会用HashMap。这样处理数据时,把数据else if的条件作为key,实现类.class作为value,维护一个HashMap。调用时,不同的数据就可以找到对应的实现类

1.3.1 首先维护一个枚举

else if的关系可以存入到枚举里,便于维护

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
java复制代码@Getter
public enum ActTemplateIdEnum {
/**
* 实现模板1
*/
IMPL_ONE(1),
/**
* 实现模板2
*/
IMPL_TWO(2),
;
private final Integer id;

ActTemplateIdEnum(Integer id) {
this.id = id;
}
}

1.3.2 维护HashMap

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
java复制代码public class ActExecutor {

private final ApplicationContext applicationContext;

@Autowired
public ActExecutor(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}

/**
* 活动实现类Map
* key: actTemplate 主键
* Value: ActAdapter 实现类
*/
private static Map<Integer, ActAdapter> actAdapterMap;

// spring加载完上下文之后,就可以把实现类作为bean注入进去
@PostConstruct
public void init() {
actAdapterMap = new HashMap<>(2);
actAdapterMap.put(TemplateIdEnum.IMPL_ONE.getId(), applicationContext.getBean(AdapterImplOne.class));
actAdapterMap.put(TemplateIdEnum.IMPL_TWO.getId(), applicationContext.getBean(AdapterImplTwo.class));
}

/**
* 根据模板id找对应的活动实现类
*
* @param templateId 模板id
* @return clz
*/
public Adapter findServiceByTemplateId(Integer templateId) {
return templateId == null || actAdapterIdx == null ? null : actAdapterIdx.get(templateId);
}

1.4 业务层调用

数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
java复制代码public class People {
/**
* 模板id
*/
private Integer templateId;
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
}

调用

1
2
3
4
5
6
7
8
9
10
11
12
java复制代码// data可以理解为业务层拿到的数据
List<People> data = new ArrayList<>();
for (People p : data) {
Adapter service = ActExecutor.findServiceByTemplateId(p.getTemplateId);
if (service != null) {
// 执行方法1
service.method1();
// 执行方法2
service.method2();
// ...
}
}

1.5 总结

定义一个通用的接口和继承该接口的不同实现类,用枚举HashMap维护else if的对应关系。业务代码就可以根据数据去HashMap中找到实现类并执行。

上述的基于接口和实现类的策略模式有点时候会有点儿笨重。比如上述的接口有两个方法,但是有几种情况只需要执行一种方法,或者还有几种情况要执行超过两个方法,那这样情况多了之后,定义接口时就要充分考虑到不同业务的兼容,这样的策略模式实现必须要充分的对业务进行抽象。

二、枚举直接实现

当时为了解决上述的问题,我看了《Effective Java》中对于枚举的用法。自己设计了一个一个策略就是一个方法的模式。

2.1 枚举

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
java复制代码@Getter
@AllArgsConstructor
public enum AdaptEnum {
/**
* 实现方法1
*/
IMPL_ONE(1) {

final Adapter adapter = SpringContextHolder.getBean(AdapterImplOne.class);

@Override
public void deal(Object param) {
// 业务实现
adapter.method1(param);
}
},
/**
* 实现方法2
*/
IMPL_ONE(2) {

final Adapter adapter = SpringContextHolder.getBean(AdapterImplTwo.class);

@Override
public void deal(Object param) {
// 业务实现
adapter.method2(param);
}
},
;

/**
* 公共抽象方法
*/
public abstract void deal(Object param);
/**
* 模板id
*/
private final Integer id;

/**
* 根据str获取枚举实例
*
* @param templateId 模板id
* @return AdaptEnum
*/
public static AdaptEnum getEnumById(Integer templateId) {
return Arrays.stream(AdaptEnum.class.getEnumConstants())
.filter(e -> Objects.equals(e.getId(), templateId))
.findFirst().orElse(null);
}

spring上下文工具

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
38
java复制代码/**
* spring容器
*
* @author sunxy
* @date:2021-01-05
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {

private static ApplicationContext applicationContext;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}

public static ApplicationContext getApplicationContext() {
assertApplicationContext();
return applicationContext;
}

public static <T> T getBean(String beanName) {
assertApplicationContext();
return (T) applicationContext.getBean(beanName);
}

public static <T> T getBean(Class<T> requiredType) {
assertApplicationContext();
return applicationContext.getBean(requiredType);
}

private static void assertApplicationContext() {
if (SpringContextHolder.applicationContext == null) {
throw new RuntimeException("ApplicationContext属性为null,请检查是否注入了SpringContextHolder!");
}
}

}

2.2 方法调用

1
2
3
4
5
6
7
8
java复制代码// data可以理解为业务层拿到的数据
List<People> data = new ArrayList<>();
for (People p : data) {
AdaptEnum e = p.getEnumById(p.getTemplateId);
if (e != null) {
e.deal(p);
}
}

2.3 总结

这样可以一个方法一个策略,就是枚举里重写的每个方法都需要引入spring的上下文,也就是说要确保枚举方法的调用一定要在spring上下文的加载完成后才行,否则会报Bean找不到的错误。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%