1. 程式人生 > 實用技巧 >策略模式幹掉if-else,switch

策略模式幹掉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));