策略模式的优缺点:
优点:
1、策略模式符合开闭原则。
2、避免使用多重条件转移语句,如if...else...语句、switch 语句
3、使用策略模式可以提高算法的保密性和安全性。
缺点:
1、客户端必须知道所有的策略,并且自行决定使用哪一个策略类。
2、代码中会产生非常多策略类,增加维护难度。
适用场景:支付方式、支付宝支付、微信支付
原文链接:https://blog.csdn.net/Leon_Jinhai_Sun/article/details/109553671
逻辑:
判断条件放在key中
对应的业务逻辑放在value中
这样子写的好处是非常直观,能直接看到判断条件对应的业务逻辑
demo项目结构:

controller:
@RestController
public class GrantTypeController {
@Autowired
private QueryGrantTypeService queryGrantTypeService;
@PostMapping("/grantType")
public String test(String resourceName){
System.out.println("resourceName = " + resourceName);
return queryGrantTypeService.getResult(resourceName);
}
}service:
@Service
public class QueryGrantTypeService {
@Autowired
private GrantTypeSerive grantTypeSerive;
private Map<String, Function<String,String>> grantTypeMap=new HashMap<>();
/**
* 初始化业务分派逻辑,代替了if-else部分
* key: 优惠券类型
* value: lambda表达式,最终会获得该优惠券的发放方式
*/
@PostConstruct
public void dispatcherInit(){
grantTypeMap.put("红包",resourceId->grantTypeSerive.redPaper(resourceId));
grantTypeMap.put("购物券",resourceId->grantTypeSerive.shopping(resourceId));
grantTypeMap.put("qq会员",resourceId->grantTypeSerive.QQVip(resourceId));
}
public String getResult(String resourceType){
//Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType
Function<String,String> result=grantTypeMap.get(resourceType);
if(result!=null){
//传入resourceId 执行这段表达式获得String型的grantType
return result.apply(resourceType);
}
return "查询不到该优惠券的发放方式";
}
}@Service
public class GrantTypeSerive {
public String redPaper(String resourceId){
//红包的发放方式
return "红包的发放方式------------>每周末9点发放";
}
public String shopping(String resourceId){
//购物券的发放方式
return "购物券的发放方式------------>每周三9点发放";
}
public String QQVip(String resourceId){
//qq会员的发放方式
return "qq会员的发放方式------------>每周一0点开始秒杀";
}
}启动类:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}测试:

总结:
switch(resourceType)
{
case "红包":
查询红包的派发方式 break;
case "购物券":
查询购物券的派发方式 break;
case "QQ会员":
break;
case "外卖会员":
break; ......default:
logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");
break;
}策略模式通过接口、实现类、逻辑分派来完成,把 if语句块的逻辑抽出来写成一个类,更好维护。
Map+函数式接口通过Map.get(key)来代替 if-else的业务分派,能够避免策略模式带来的类增多、难以俯视整个业务逻辑的问题。
版权声明:本文为qq_52145053原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。