【JAVA设计模式】策略模式

1.什么是策略模式?

策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理,相同的事情-----选择不用同方式 (不同实现)举例子,最终可以实现解决多重if判断问题。

2.策略模式优缺点?

1.优点 算法可以自由切换(高层屏蔽算法,角色自由切换) 避免使用多重条件判断(如果算法过多就会出现很多种相同的判断,很难维护) 扩展性好(可自由添加取消算法 而不影响整个功能) 2.缺点 策略类数量增多(每一个策略类复用性很小,如果需要增加算法,就只能新增类) 所有的策略类都需要对外暴露(使用的人必须了解使用策略,这个就需要其它模式来补充,比如工厂模式、代理模式)

3.策略模式的使用场景

2.排序算法 冒泡/简单选择/堆排序等 4.快递 申通、圆通、京东、德邦、顺丰等

4.案例(联合登录)

1.创建登录的service

/**
 * @desc: 策略模式
 * @author: xhs
 * @date: 2022/6/12 11:17
 * @version: JDK 1.8
 */
public interface LoginStrategyService {

    /**
     * 登录
     * @return
     */
   String login();
}
/** * @desc: 策略模式 * @author: xhs * @date: 2022/6/12 11:17 * @version: JDK 1.8 */ public interface LoginStrategyService { /** * 登录 * @return */ String login(); }

3.创建登录的controller

package com.xhs.pattern.strategy.controller;

import com.xhs.pattern.dto.request.LoginRequest;
import com.xhs.pattern.strategy.service.LoginStrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @desc: 策略模式
 * @author: xhs
 * @date: 2022/6/12 11:01
 * @version: JDK 1.8
 */

@RestController
@RequestMapping("/login")
public class StrategyController {

    @Autowired
    private Map<String, LoginStrategyService> loginStrategyServiceMap;
    
    /**
     * 策略模式登录
     * @param loginRequest
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestBody LoginRequest loginRequest) {
        LoginStrategyService loginStrategyService = loginStrategyServiceMap.get(loginRequest.getLoginType());
        String login = loginStrategyService.login();
        return login;
    }

}
package com.xhs.pattern.strategy.controller; import com.xhs.pattern.dto.request.LoginRequest; import com.xhs.pattern.strategy.service.LoginStrategyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /** * @desc: 策略模式 * @author: xhs * @date: 2022/6/12 11:01 * @version: JDK 1.8 */ @RestController @RequestMapping("/login") public class StrategyController { @Autowired private Map loginStrategyServiceMap; /** * 策略模式登录 * @param loginRequest * @return */ @PostMapping("/login") public String login(@RequestBody LoginRequest loginRequest) { LoginStrategyService loginStrategyService = loginStrategyServiceMap.get(loginRequest.getLoginType()); String login = loginStrategyService.login(); return login; } }

5.测试

经验分享 程序员 微信小程序 职场和发展