策略模式

大家好,我是连边,这是我的第46篇原创文章。

这一篇文章不长,主要就是通过几行代码来实现一个我们常说的策略模式

什么策略模式

比如我们需要实现一个两个数的加、减、乘、除的计算器。

一般的写法会这样子写:

计算器实现方法ifelse版本

或者

计算器实现方法switch版本

上边都是很直男的解决方式,为了后期方便扩展,而又对原来的代码无侵入性,其实可以使用策略模式根据我们的运算符号来对两个数字作不同的运算这是我们抽象出来的需求。

基于我们Spring注解,可以很简单的实现我们的策略模式(这一点被同事笑话了,包括我之前的文章里面,都用到了代理模式来实现策略模式,后来发现是交了代码智商税。)

基于Spring注解的解决方案

创建计算器接口类

1
2
3
4
5
6
7
8
9
10
@Service
public interface ICalc {
/**
* 计算器的运算方法
* @param i
* @param j
* @return
*/
int operation(int i, int j);
}

分别创建加减乘除运算类

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
@Service("add")
public class AddCalc implements ICalc{
@Override
public int operation(int i, int j) {
return i+j;
}
}

@Service("sub")
public class SubCalc implements ICalc{

@Override
public int operation(int i, int j) {
return i-j;
}
}

@Service("mult")
public class MultCalc implements ICalc{
@Override
public int operation(int i, int j) {
return i*j;
}
}

@Service("div")
public class DivCalc implements ICalc{
@Override
public int operation(int i, int j) {
return i/j;
}
}

依赖注入使用:

1
2
@Autowired
Map<String, ICalc> calcMap;

调用控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 调用的URL:
* http://127.0.0.1:8001/user/calc/add 加法调用
* http://127.0.0.1:8001/user/calc/sub 减法调用
* http://127.0.0.1:8001/user/calc/mult 乘法调用
* http://127.0.0.1:8001/user/calc/div 除法调用
* @param opStr 运算符
* @return
*/
@GetMapping(path = "/calc/{opStr}")
public String op(@PathVariable String opStr) {
ICalc calc = calcMap.getOrDefault(opStr, null);
if (null == calc) {
return "没有找到正确的策略";
}

int i = 1;
int j = 2;
return calc.operation(i, j) + "";
}

完整的代码:https://github.com/lianbian/EhCache

总结

依赖Spring的依赖注入实现优雅的策略模式,告别各种if elseswitch以及代理或者自定义注解实现策略模式


策略模式
https://www.lianbian.net/设计模式/5f304de4d3ee.html
作者
连边
发布于
2021年10月28日
许可协议