目录
2.2.1 、新建PolicyPatternController.java
2.2.3 、定义一个接口:PolicyPatternService.java
2.2.4 、定义3个实现类来实现 PolicyPatternService 接口
策略模式是一种设计模式,它允许在运行时动态选择算法的行为。它定义了一系列算法,并将每个算法都封装到了一个独立的类中,这些算法可以相互替换使用。在策略模式中,一个类的行为或算法可以在运行时进行更改,而不必修改它的结构。
Context(上下文):持有一个策略对象的引用,并调用策略对象提供的算法。
Strategy(策略):定义所有支持的算法的公共接口,并提供具体的实现。
ConcreteStrategy(具体策略):实现 Strategy 接口,提供具体的算法实现。
策略模式可以帮助我们避免出现大量的 if-else 语句或 switch 语句,使得代码更加简洁、易于维护和扩展。它广泛应用于需要动态地切换算法的场景,例如排序、搜索等算法。
根据传入不同的类型,从而进行不同的处理
- @Service
- public class TesiImpl implements PolicyPatternService {
-
-
-
- @Override
- public String sayHello(String type) {
- if ("1".equals(type)) {
- // TODO 具体业务代码
- }
- if ("2".equals(type)) {
- // TODO 具体业务代码
- }
- if ("3".equals(type)) {
- // TODO 具体业务代码
- }
- if ("4".equals(type)) {
- // TODO 具体业务代码
- }
- .................................
-
- return null;
- }
- }
这种写法可读性差,后期不易于维护项目。。。。。。
- @RestController
- @RequestMapping("celue")
- @Slf4j
- public class PolicyPatternController {
-
- @Autowired
- private List
policyPatternService; -
- @PostMapping("test")
- public Result test(@RequestBody Express expres) {
- PolicyPatternService service = policyPatternService.
- stream().
- filter(l -> l.isCeLueModel(expres.getType())).findFirst().orElse(null);
- String name = service.sayHello();
- return Result.ok(name);
- }
- }
- @Data
- public class Express {
-
- @ApiModelProperty("根据不同的类型实现不同的方法")
- private String type;
-
- }
-
- public interface PolicyPatternService {
-
- //判断传入的类型
- Boolean isCeLueModel(String type);
-
- // 方法
- String sayHello();
- }
1. JDServcieImpl.java
- @Service
- public class JDServcieImpl implements PolicyPatternService {
-
- //判断传入的类型
- @Override
- public Boolean isCeLueModel(String type) {
- return Objects.equals(type, "1");
- }
-
- @Override
- public String sayHello() {
- // TODO 具体业务代码
- return "我是京东";
- }
- }
2. YZServcieImpl.java
- @Service
- public class YZServcieImpl implements PolicyPatternService {
-
- //传入的类型
- @Override
- public Boolean isCeLueModel(String type) {
- return Objects.equals(type, "2");
- }
-
- @Override
- public String sayHello() {
- // TODO 具体业务代码
- return "我是邮政";
- }
- }
3. ZTServcieImpl.java
- @Service
- public class ZTServcieImpl implements PolicyPatternService {
-
- //判断传入的类型
- @Override
- public Boolean isCeLueModel(String type) {
- return Objects.equals(type, "3");
- }
-
- @Override
- public String sayHello() {
- // TODO 具体业务代码
- return "我是中通";
- }
- }
4. 测试效果 type = 1

5. 测试效果 type = 2

6. 测试效果 type = 3
