策略模式干掉if-else,switch
1.传统if -else 写法
String nodeModelStr = "";
if (nodeType == NodeType.START){
StartModel startModel = JSON.parseObject(nodeModelStr,StartModel.class)
}else if(nodeType == NodeType.END){
EndModel endModel = JSON.parseObject(nodeModelStr,EndModel.class)
}
2.策略模式写法
使用了lambda表示里,map里key是NodeType,value是方法对象Function<String,BaseModel>(方法入参是String类型,返回值类型是BaseModel)
如下示例中nodeModelStr就是方法入参,返回值是BaseModel
private static Map<NodeType, Function<String,BaseModel>> checkModelTypeDispatcher = new HashMap<NodeType, Function<String, BaseModel>>(){{
put(NodeType.START,nodeModelStr -> JSON.parseObject(nodeModelStr,StartModel.class));
put(NodeType.END,nodeModelStr -> JSON.parseObject(nodeModelStr,EndModel.class));
}};
Function<String,BaseModel> function = checkModelTypeDispatcher.get(nodeType);
BaseModel baseModel = function.apply(JSON.toJSONString(node));
3.策略模式的变种
创建策略集合
/**
* 策略集合
*/
Map<ResGroupType, Consumer<ProcessContext<NotificationModel>>> strategyRelation = new ImmutableMap.Builder<ResGroupType, Consumer<ProcessContext<NotificationModel>>>()
.put(ResGroupType.CONFIG_RES_GROUP, rewriteConfigResGroupStrategy)
.put(ResGroupType.VIRTUAL_RES_GROUP, rewriteVirtualResGroupStrategy)
.build();
创建带参数的获取策略的方法
@Override
public Consumer<ProcessContext<NotificationModel>> getStrategy(ResGroupType resGroupType) {
Consumer<ProcessContext<NotificationModel>> consumer = strategyRelation.get(resGroupType);
return Optional.ofNullable(consumer).orElseThrow(() -> new RuntimeException("获取执行策略异常"));
}
主函数执行
this.getStrategy(notificationModel.resGroupType).accept(context);
原创:做时间的朋友

浙公网安备 33010602011771号