- 什么是策略模式
策略模式是一种行为型模式,它将对象和行为分开,将行为定义为 一个行为接口 和 具体行为的实现。策略模式最大的特点是行为的变化,行为之间可以相互替换。每个if判断都可以理解为就是一个策略。本模式使得算法可独立于使用它的用户而变化。
简单理解就是,针对不同的场景,使用不同的策略进行处理。 - 策略模式在我的项目中的应用
- 不同的业务场景的数据导入,如发票数据导入,进项明细数据导入等等等
- 根据不同的计算规则计算外包人力成本:
人天累积 = 人天单价 * 出勤天数
月价格计算(A类方案)= 单价/20.83 * 出勤天数
月价格计算(B类方案)= 单价/当月工作日总数 * 出勤天数
月价格计算(C类方案)= 单价/21.75 * 出勤天数 - 导出excel或csv文件
- 导出excel或csv文件代码实例
##1.定义一个导出接口
public interface DownloadService {
void exportDownloadFile();
}
##2.导出excel和scv文件会有一些相同的行为,再定义一个抽象方法继承DownloadService
public abstract class AbstractDownloadThreadService implements DownloadThreadService {
@Override
public abstract void exportDownloadFile() throws SQLException;
}
##3.定义cvs处理类继承抽象类
@Service("csvDownloadService")
public class CsvDownloadServiceImpl extends AbstractDownloadThreadService{
@Override
public void exportDownloadFile() {
}
}
##4.定义excel处理类继承抽象类
@Service("xlsxDownloadService")
@RefreshScope
public class ExcelDownloadServiceImpl extends AbstractDownloadThreadService {
@Override
public void exportDownloadFile() {
}
}
##5.我这边bean都是交给spring去管理的,controller直接根据name 调用就行
@RestController
public class DownloadController{
@Autowired Map<String,DownloadService> downloadServiceMap;
@ApiOperation(value="导出文件到本地",hidden=true)
@PostMapping("/exportAtLocal")
@ResponseBody
public AjaxResult exportAtLocal(@RequestParam(name = "type") String type) throws SQLException {
downloadThreadServiceMap.get(type+"DownloadThreadService").exportDownloadFile();
return AjaxResult.success("exporting");
}
}