策略模式
代码中使用大量if 使用策略优化
将不同的业务需求类 整合成一个接口
通过多个实现类实现业务代码的拆分
1、定义一个公用的接口
import com.spring.Component;
@Component
public interface ImgZipStrategy {
/**
* 获取不同策略的标识
*/
String getZipType();
/**
* 封装公用算法
*/
String zipWork(ImgCompressQO qo);
}
2、定义不同的实现策略
以图片压缩为例子 数据源分为了 base64、文件路径、url
2.1 数据源为base64 实现的实现类
import com.spring.Component;
/**
* Base64格式的图片压缩 策略
*/
@Component
public class ImgZipByBase64Impl implements ImgZipStrategy {
@Override
public String getZipType() {
return "base64业务逻辑";
}
@Override
public String zipWork(ImgCompressQO qo) {
return "base64处理逻辑";
}
}
2.2 数据源为filePath实现的实现类
import com.spring.Component;
/**
* 文件路径的图片压缩 策略
*/
@Component
public class ImgZipByFilePathImpl implements ImgZipStrategy {
@Override
public String getZipType() {
return "flilePath处理逻辑";
}
@Override
public String zipWork(ImgCompressQO qo) {
return "flilePath处理逻辑";
}
}
2.3 数据源为Url实现的实现类
import com.spring.Component;
/**
* Url格式的图片压缩 策略
*/
@Component
public class ImgZipByUrlhImpl implements ImgZipStrategy {
@Override
public String getZipType() {
return "flilePath处理逻辑";
}
@Override
public String zipWork(ImgCompressQO qo) {
return "flilePath处理逻辑";
}
}
3.入口
3.1 通过实现 ApplicationContextAware 初始化的时候加载所有策略的实现类。
3.2 维护内部Map Key为实现类的标识,V为接口类型。
3.3 通过入参,执行不同的策略逻辑。
@Component
public class ImgZipService implements ApplicationContextAware {
@Resource
private final Map<String, ImgZipStrategy> imgZipStrategyMap = new ConcurrentHashMap<>();
public CommonResult doImgZip(ImgCompressQO qo) {
//通过入参传递对应的实现标识 拿到对应的策略实现类
ImgZipStrategy imgZipStrategy = imgZipStrategyMap.get(qo.getSrcDataType);
//调用对应的实现类的方法
imgZipStrategy.zipWork(qo);
}
@Override
public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
//将不同的策略放入到map中
Map<String, ImgZipStrategy> beansOfType = applicationContext.getBeansOfType(ImgZipStrategy.class);
beansOfType.values().forEach(imgZipStrategy -> imgZipStrategyMap.put(imgZipStrategy.getZipType(), imgZipStrategy));
}
}
}