策略模式:
在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。
策略的对象和一个行为绑定在一块,利用枚举实现一下、核心代码全部贴出如下
1.一个接口(用于别的业务只需用调用该接口即可)
/**
* Strategy Pattern 策略模式
*/
public interface EntityApi {
void computeEntity(ProcessInstantsListVO processInstantsListVO, String id);
}
2.根据业务不同(行为不同)我们分别对接口实现。 (真正的业务实现在这里就可以了)
只列出一个实现类作为参考 ,我这里写的大约十个实现类 根据业务而来
@Component
public class ComponentMaterialApi implements EntityApi {
@Resource
private ComponentMaterialRepository componentMaterialRepository;
@Override
public void computeEntity(ProcessInstantsListVO processInstantsListVO, String id) {
componentMaterialRepository.findById(id).ifPresent(e ->
processInstantsListVO.setEntityTypeName(e.getProject() != null ? e.getProject().getProjectName() : "")
);
}
}
3.重点 枚举类
@Getter
@Component
public enum WorkFlowTypeEnum {
WORK_FLOW_TYPE_ONE("ProjectType", "项目审批", ProjectServiceApi.class),
WORK_FLOW_TYPE_TWO("ProductListType", "总成品清单审批", ProductListServiceApi.class) ,
WORK_FLOW_TYPE_THREE("ProduceMouldType", "模具清单批",ProduceMouldApiServiceApi.class),
WORK_FLOW_TYPE_FOUR("ComponentMaterialType", "构件物资审批",ComponentMaterialApi.class),
WORK_FLOW_TYPE_FIVE("TotalDemandPlanType", "物资总需求计划审批",TotalDemandPlanServiceApi.class);
private String value;
private String name;
private EntityApi serviceApi;
WorkFlowTypeEnum(String value, String name, Class<? extends EntityApi> apiClazz) {
this.value = value;
this.name = name;
try {
this.serviceApi = apiClazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
重点在于构造函数上面。利用了接口特性。
4.业务应用
WorkFlowTypeEnum enumByValue = WorkFlowTypeEnum.getEnumByValue(byProcessInstantsId.getEntityType());
SpringUtil.getBean(enumByValue.getServiceApi().getClass()).computeEntity(processInstantsListVO, byProcessInstantsId.getEntityId());
总结:
这样就可以在实现类上面对业务进行实现就行了。 也就是说我们不在关心其他的步骤,只需要配置枚举,然后写一个实现类就可以了
大大减少开发精力。
补充一点 我们也可以给枚举一个抽象方法。对,每一个枚举对抽象方法的实现也是可以的 。但是不是太优美 还是推荐第一种。如果说还有别的功能需要实现 我们两种方法同时用也是可以的。