Springboot integrated strategy mode concept -> usage scenarios -> advantages and disadvantages -> enterprise-level actual combat

I. Introduction

The strategy pattern may be the most used at work, and it is also the most frequently mentioned in interviews. It is a must for code refactoring and optimization!
The editor has always said before that, in fact, there is no real actual combat; recently, I have the opportunity to do actual combat, so I will share my experience and use it at the enterprise level!

2. Strategy mode

1. What is the strategy pattern

Strategy mode, the full English name is Strategy Design Pattern. In the GoF book "Design Patterns", it is defined like this:

Define a family of algorithm classes, classify each 算法分别封装起来, so that they can 互相替换. The Strategy pattern can make changes to algorithms independent of the clients that use them (clients here refer to the code that uses the algorithms).

2. The structure of the strategy pattern

  • Strategy: Abstract strategy class, generally an interface or strategy class
  • ConcreteStrategy: concrete algorithm implementation strategy class
  • Context: environment or context class, used to uniformly execute specific strategies

In fact, the above three parts are explained in vernacular:
an interface and strategy are needed to standardize and constrain the interface and method. At this time, some specific implementation algorithm classes are needed to inherit or implement the interface and strategy just now. Finally, through an environment or context, also It can be called the factory to call the specific algorithm according to the type!

3. Usage scenarios

  • Avoid lengthy if-else or switch branch judgments
  • Need to dynamically choose one of several algorithms
  • The implementation details of specific strategies (algorithms) are hidden from customers, completely independent of each other, and the rest of the extension will not be affected

Specific scenarios are generally:

  • payment method selection
  • Choice of discount and full discount
  • Different systems are called according to the type

4. Advantages and disadvantages

advantage:

  • Good scalability
  • Comply with the principle of opening and closing
  • Complies with the Single Responsibility Principle
  • good readability
  • Easy to maintain
  • Avoid multiple layers of judgment

shortcoming:

  • There are too many strategies, resulting in the strategy class
  • Not friendly to novices reading code

3. Actual combat in strategy mode

1. Practical examples

Today, the editor demonstrates the usage plan of the strategy mode according to the different things that need to be done in the four seasons of spring, summer, autumn and winter; the
demand is:
if it is spring, you must go to fly a kite;
if it is summer, you must go swimming;
if it is autumn, you must go to see Maple Leaf
If it is winter, you have to go to a snowball fight
If you don't use the strategy mode, it must
be implemented with if-if else!
Let's take everyone to experience the specific use! !

2. Policy interface

/**
 * 四季策略
 * @author wangzhenjun
 * @date 2022/12/1 9:30
 */
public interface SeasonsStrategy {
    
    

    /**
     * 根据季节去执行不同的方案
     * @param seasons
     * @return
     */
    String execute(String seasons);
}

3. Spring implementation

/**
 * 春季具体实现
 * @author wangzhenjun
 * @date 2022/12/1 9:34
 */
// 指定容器的名称,不指定默认为类名称首字母小写
@Component("spring")
public class SpringStrategy implements SeasonsStrategy{
    
    
    @Override
    public String execute(String seasons) {
    
    

        return seasons + "来了!我们一起去放风筝吧!";
    }
}

4. Summer implementation

/**
 * 夏季具体实现
 * @author wangzhenjun
 * @date 2022/12/1 9:34
 */
// 指定容器的名称,不指定默认为类名称首字母小写
@Component("summer")
public class SummerStrategy implements SeasonsStrategy{
    
    
    @Override
    public String execute(String seasons) {
    
    

        return seasons + "来了!我们一起去游泳吧!";
    }
}

5. Concrete implementation in autumn

/**
 * 秋季具体实现
 * @author wangzhenjun
 * @date 2022/12/1 9:34
 */
// 指定容器的名称,不指定默认为类名称首字母小写
@Component("autumn")
public class AutumnStrategy implements SeasonsStrategy{
    
    
    @Override
    public String execute(String seasons) {
    
    

        return seasons + "来了!我们一起去放看枫叶吧!";
    }
}

6. Implementation in winter

/**
 * 冬季具体实现
 * @author wangzhenjun
 * @date 2022/12/1 9:34
 */
// 指定容器的名称,不指定默认为类名称首字母小写
@Component("winter")
public class WinterStrategy implements SeasonsStrategy{
    
    
    @Override
    public String execute(String seasons) {
    
    

        return seasons + "来了!我们一起去打雪仗吧!";
    }
}

7. Context factory implementation

private Map<String, SeasonsStrategy> seasonsMap;This is the most important thing. Many times we know how to implement strategies and how to write them, but we don’t know how to put them in in a unified way and call them. We can put them in the map by ourselves. Of course, spring has already been assembled for us, just call it on demand!

core:
Spring will automatically inject the implementation class of the Strategy interface into this Map, the key is the bean id, and the value is the corresponding strategy implementation class!

/**
 * 环境或者上下文类,用于统一执行具体策略
 * @author wangzhenjun
 * @date 2022/12/1 9:56
 */
@Component
public class SeasonsFactory {
    
    
    /**
     * Spring会自动将Strategy接口的实现类注入到这个Map中,key为bean id,value值则为对应的策略实现类
     */
    @Autowired
    private Map<String, SeasonsStrategy> seasonsMap;

    /**
     * 处理四季统一入口方法
     * @param seasons
     * @param beanName
     * @return
     */
    public String handle(String seasons,String beanName){
    
    
    	// 根据bean的名称获取对应的算法处理类
        SeasonsStrategy seasonsStrategy = seasonsMap.get(beanName);
        String execute = seasonsStrategy.execute(seasons);
        return execute;
    }
}

8. Controller processing

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    
    
	
    @Autowired
    private SeasonsFactory seasonsFactory;

    @GetMapping("/strategyTest/{seasons}/{beanName}")
    public Result strategyTest(@PathVariable("seasons") String seasons,@PathVariable("beanName") String beanName){
    
    
        String handle = seasonsFactory.handle(seasons, beanName);
        return Result.success(handle);
    }
}

9. Test

http://localhost:8087/test/strategyTest/春天/spring
insert image description here
http://localhost:8087/test/strategyTest/夏天/summer
insert image description here

Four. Summary

A series of algorithms are defined in the strategy mode, each algorithm is encapsulated, and they can be replaced without affecting each other.

The strategy mode benefits from 开闭原则the design according to the design, and each specific algorithm is designed according to 单一职责原则the design; it is improved 代码的复用性, the implementation details of the specific strategy (algorithm) are hidden from the client, and they are completely independent from each other, and the rest of the expansion is not affected; avoid if-else 或 switch 分支sentence judgment; its disadvantage is that the client must Knowing all policy classes increases the number of classes in the system.

In daily development, it is generally used to eliminate multiple judgments. Sometimes it is not necessary 用设计模式而用设计模式, and it must be combined with business scenarios, 过度设计which is also fatal! !

If it is helpful to you, please don't be stingy with your little hands of making a fortune. Your one-click three-link is the driving force for my writing, thank you everyone! !


You can take a look at the editor's WeChat official account, and read the first articles on the website. Welcome to pay attention and communicate together! !

Click to visit! The editor's own website also has many good articles!

Guess you like

Origin blog.csdn.net/qq_52423918/article/details/128119400