策略模式是什么?
是一种行为型的设计模型,在这种模式中一个类的行为或其算法可以在运行时更改。根据运行时的条件选择不同的运行行为或者算法。
使用枚举 + 策略模式场景:
在商城项目中,进行商品结算之后,对于虚拟商品还要进行特殊处理,对于不同的虚拟商品存在不同的处理方式。但是又不想直接用 if else , 如果虚拟商品类型过多,导致 if else 很多看起来很长。
具体实现过程
- 新增一个接口 (StrategyCommonService),将虚拟商品的公共方法进行提取,定一个统一的虚拟商品处理方法
- 新增具体的实现(StrategyCommonService)接口的子类,分别为 (StrategyAServiceImpl) 和 (StrategyBServiceImpl),重写接口定义的方法
- 添加枚举,对(StrategyAServiceImpl、StrategyBServiceImpl)的 beanName 和 虚拟商品类型进行映射,并添加通过虚拟商品类型返回具体的beanName 的静态方法
- 调用-> 通过类型获取 beanName, 然后从 ApplicationContext 里面通过 beanName 获取类,进行强转成接口,并调用执行方法。
Springboot(Java)
public interface StrategyCommonService {
public void commonMethod();
}
@Service("strategyAServiceImpl")
public class StrategyAServiceImpl implements StrategyCommonService{
@Override
public void commonMethod() {
System.out.println(" 执行 A 策略");
}
}
@Service("strategyBServiceImpl")
public class StrategyBServiceImpl implements StrategyCommonService{
@Override
public void commonMethod() {
System.out.println(" 执行 B 策略");
}
}
@Getter
public enum StrategyEnum {
ONE(1, "strategyAServiceImpl"),
TWO(2, "strategyBServiceImpl"),
;
private int type;
private String beanName;
StrategyEnum(int type, String beanName) {
this.type = type;
this.beanName = beanName;
}
public static String getBeanName(int type) {
for (StrategyEnum value : StrategyEnum.values()) {
if(value.type == type) {
return value.getBeanName();
}
}
return null;
}
}
@RestController
public class StrategyController {
@Autowired
private ApplicationContext applicationContext;
@RequestMapping("/test")
public void first(@PathParam("type") int type) {
String beanName = StrategyEnum.getBeanName(type);
StrategyCommonService strategyCommonService = (StrategyCommonService)applicationContext.getBean(beanName);
strategyCommonService.commonMethod();
}
}