项目中使用到枚举策略模式,故对此作出总结
场景:公司做末端配送,需要将公司驿站与四通一达等快递公司对接,包括驿站信息创建,修改,包裹信息同步,轨迹查询;
预期:暴露给前端一个接口,前端传入不同快递公司类型和不同操作类型,决定具体的实现;
策略模式三个重要部分:
抽象角色: 具体要对什么操作进行抽象;
具体角色实现:基于抽象角色进行不同实现;
上下文切换类:这里使用枚举进行具体实现的转发;
·~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
整体思路:
多态是基础,假设有中通,申通,百事,韵达,四家快递公司需要对接,这四家快递公司都有createHub(创建驿站),updateHub(修改驿站)collection (入库揽收快递)三个操作;那么首先从实现上,需要抽取baseLogisticesSeriver(基础物流服务)里面三个接口createHub,updateHub,collection;不同的快递公司再具体实现不同业务逻辑;
那么如何根据不同快递公司进入到不同的实现类里去呢,又怎么根据不同操作找到具体方法呢?这个时候就需要定义枚举帮助我们找到具体实现类中的具体方法;
//找到具体实现类,抽象一个行为进行具体方法转发
public enum OperationPlatform {
YTO("圆通", YtoServiceImpl.class),
STO("申通", StoServiceImpl.class),
YUNDA("韵达", YunDaServiceImpl.class),
ZTO("中通", ZtoServiceImpl.class);
private final String description;
private final Class<? extends baseLogisticesSeriver> clazz;
public String matchPlatform() {
return Introspector.decapitalize(clazz.getSimpleName());
}
}
//找到具体实现方法
public enum SynchronizationState {
RECEIVED("揽收") {
@Override
public void command(baseLogisticesSeriver logisticsService) {
logisticsService.collection();
}
},
REGISTER_STATION("注册驿站") {
@Override
public void command(baseLogisticesSeriver logisticsService) {
logisticsService.createHub();
}
},
UPDATE_STATION("修改驿站信息") {
@Override
public void command(baseLogisticesSeriver logisticsService) {
logisticsService.updateHub();
}
};
private final String description;
SynchronizationState(String description) {
this.description = description;
}
public abstract void command(baseLogisticesSeriver logisticsService);
}
public class test {
/**
* spring注入
*/
@Autowired
private Map<String, baseLogisticesSeriver> baseLogisticesSeriverMap;
@GetMapping("/test")
public void test(SynchronizationRequest synchronizationRequest){
//OperationPlatform枚举找到具体实现类
baseLogisticesSeriver seriver = baseLogisticesSeriverMap.get(synchronizationRequest.getOperationPlatform().matchPlatform());
//将具体实现传入,SynchronizationState同步状态枚举,执行具体方法
synchronizationRequest.getSynchronizationState().command(seriver);
}
}
缺点:策略模式需要把所有的策略暴露给客户端,相当于把代码证的if else逻辑组合,交给客户端决定;
优点:基于多态,实现清晰,方便拓展;