1.設計模式選型---行為型(策略模式),為消除if-else 實現代碼的松耦合而存在
2.思路:將行為的決策權交給枚舉,有多少種情況就需要定義多少個枚舉類型,匹配時根據枚舉類型中的鍵值進行決策。
3.talk is cheap, show me the code
4.代碼實現:
4.1定義一個超級父類SuperInterface,多個策略模式時可直接拿來復用:
1 import java.util.List; 2 3 /** 4 * 策略模式最頂層的父類 5 * @author HUAWEI 6 * 7 */ 8 public interface SuperInterface { 9 10 public Object doOperation(List objs); 11 12 }
4.2.定義業務具體實現,此處借用加減操作進行封裝(OperationAdd)
1 import java.util.List; 2 3 public class OperationAdd implements SuperInterface { 4 5 private static OperationAdd add = null; 6 7 private OperationAdd(){} 8 9 public static OperationAdd getInstance(){ 10 if(add == null){ 11 synchronized (OperationAdd.class) { 12 add = new OperationAdd(); 13 } 14 } 15 return add; 16 } 17 @Override 18 public Object doOperation(List objs) { 19 double sum = 0; 20 for(Object obj:objs){ 21 double temp = Double.valueOf(obj.toString()); 22 sum += temp; 23 } 24 return sum; 25 } 26 27 }
4.3.定義業務具體實現,此處借用加減操作進行封裝(OperationSub)
1 import java.util.List; 2 3 public class OperationSub implements SuperInterface { 4 5 6 private OperationSub(){} 7 8 private static OperationSub sub = null; 9 10 public static OperationSub getInstance(){ 11 if(sub == null){ 12 synchronized (OperationSub.class) { 13 sub = new OperationSub(); 14 } 15 } 16 return sub; 17 } 18 @Override 19 public Object doOperation(List objs) { 20 double First = Double.valueOf(objs.get(0).toString()); 21 int i=0; 22 for(Object d:objs){ 23 if(i == 0){ 24 i =1; 25 continue; 26 } 27 double temp = Double.valueOf(d.toString()); 28 First -= temp; 29 } 30 return First; 31 } 32 33 }
4.4.枚舉類定義(OperType)
1 public enum OperType { 2 3 ADD(1,OperationAdd.getInstance()),SUB(2,OperationSub.getInstance()); 4 private Integer code; 5 private SuperInterface option; 6 private OperType(Integer code,SuperInterface option){ 7 this.setCode(code); 8 this.setOption(option); 9 } 10 public SuperInterface getOption() { 11 return option; 12 } 13 public void setOption(SuperInterface option) { 14 this.option = option; 15 } 16 public Integer getCode() { 17 return code; 18 } 19 public void setCode(Integer code) { 20 this.code = code; 21 } 22 }
4.5.業務具體類(test)
1 import java.util.HashMap; 2 import java.util.Map; 3 4 import net.sf.json.JSONArray; 5 6 7 8 9 public class test { 10 11 public static void main(String[] args) { 12 Map request = new HashMap<String, String>(); 13 request.put("type", "SUB"); 14 request.put("data", "[100,20,30]"); 15 doOperation(request); 16 } 17 18 public static void doOperation(Map<String,String> request){ 19 try{ 20 String type = request.get("type"); 21 String data = request.get("data"); 22 JSONArray array = JSONArray.fromObject(data); 23 OperType optype = OperType.valueOf(type); 24 SuperInterface add = optype.getOption(); 25 Object res = add.doOperation(array); 26 System.out.println("add res:"+res); 27 }catch(Exception e){ 28 System.out.println("執行出錯"); 29 e.printStackTrace(); 30 } 31 } 32 }
5.說明:具體類實現時用到了單例模式,避免多次實例化造成內存浪費,使用枚舉有些類似switch形式,但是具體匹配需要交給前端傳值來調用,情況過多時前后台交互的情況過多,不利於前端代碼的更改