SpringBoot下策略模式变体
需求
在医院的体检系统中, 会根据体检者的类型不同, 生成不同的体检结论。
通常体检者的类型分为健康体检 、 公务员体检 、 职业病体检
请根据以上体检类型分别生成不同的体检结论。
UML
代码
体检类型枚举
@Getter
public enum PhysicalExaminationTypeEnum {
HEALTH_CHECKUP("健康体检"),
OCCUPATIONAL_DISEASE_EXAMINATION("职业病体检"),
CIVIL_SERVANT_PHYSICAL_EXAMINATION("公务员体检");
private final String value;
PhysicalExaminationTypeEnum(String value) {
this.value = value;
}
}
策略
策略接口
public interface ConclusionStrategy {
String generateConclusion(PhysicalExaminationResultData resultData);
String getType();
}
健康体检结论策略
@Component
public class HealthConclusionStrategy implements ConclusionStrategy {
@Override
public String generateConclusion(PhysicalExaminationResultData resultData) {
return "健康体检结论策略";
}
@Override
public String getType() {
return PhysicalExaminationTypeEnum.HEALTH_CHECKUP.getValue();
}
}
公务员体检结论策略
@Component
public class CivilServantConclusionStrategy implements ConclusionStrategy {
@Override
public String generateConclusion(PhysicalExaminationResultData resultData) {
return "公务员结论";
}
@Override
public String getType() {
return PhysicalExaminationTypeEnum.CIVIL_SERVANT_PHYSICAL_EXAMINATION.getValue();
}
}
职业病体检结论策略
@Component
public class OccupationalDiseaseConclusionStrategy implements ConclusionStrategy {
@Override
public String generateConclusion(PhysicalExaminationResultData resultData) {
return "职业病体检结论";
}
@Override
public String getType() {
return PhysicalExaminationTypeEnum.OCCUPATIONAL_DISEASE_EXAMINATION.getValue();
}
}
上下文处理器
为调用方 提供了统一的方法, 我通常喜欢称其为上下文处理器
@Component
public class ConclusionContextHandler {
Map<String, ConclusionStrategy> strategyMap;
@Autowired
public ConclusionContextHandler(List<ConclusionStrategy> strategies) {
this.strategyMap = strategies.stream()
.collect(Collectors.toMap(ConclusionStrategy::getType, s -> s));
}
public String getConclusion(String physicalExamNo) {
final String physicalExaminationType =
final PhysicalExaminationResultData resultData =
return strategyMap.get(physicalExaminationType).generateConclusion(resultData);
}
}
Restful接口
@RestController
@RequestMapping("/conclusion")
public class GeneralInspectionController {
@Resource
ConclusionContextHandler conclusionContextHandler;
@GetMapping("/{physicalExamNo}")
public CommonResult<String> getGeneralInspectionConclusion(@PathVariable("physicalExamNo") String physicalExamNo) {
return CommonResult.success(conclusionContextHandler.getConclusion(physicalExamNo));
}
}
|