-
使用很多if else的场景
-
public void save(String type,Object data){if("db".equals(type)){saveInDb(data);}else if("file".equals(type)){saveInFile(data);}else if("oss".equals(type)){saveInOss(data);}}
-
-
使用枚举来解决
-
public enum SaveStrategyEnum{DB("db"){@Overridepublic void save(Object obj){System.out.println("save in db:"+obj);}},FILE("file"){@Overridepublic void save(Object obj){System.out.println("save in file:"+ obj);}},OSS("oss"){@Overridepublic void save(Object obj){System.out.println("save in oss:" +obj);}};private String type;SaveStrategyEnum(String type){this.type = type;}public abstract void save(Object obj);public static SaveStrategyEnum typeOf(String type){for(SaveStrategyEnum strategyEnum : values()){if(strategyEnum.type.equalsIgnoreCase(type)){return strategyEnum;}}return null;} }public void save(String type,Object data){SaveStrategyEnum strategyEnum = SaveStrategyEnum.typeOf(type);if(strategyEnum != null){strategyEnum.save(data);} }
-