我有一个java控制器类,当在任何项目中调用保存操作时,例如Product或coverage或Limit,它调用控制器保存方法并传递参数。控制器中的if逻辑检查参数并调用相应对象的save方法。 if逻辑日益增长。任何人都可以建议更好的设计模式吗?
代码:
public class Product {
public void save(PolicyData p){
//logic here
}
}
public class Coverage {
public void save(PolicyData p){
//logic here
}
}
public class Limit {
public void save(PolicyData p){
//logic here
}
}
public class Controller {
private Product pr=new Product();
private Limit lim=new Limit();
private Coverage cov=new Coverage();
public void save(PolicyData p,String item){
if(item.equals("Product")){
pr.save(p);
}if(item.equals("Coverage")){
cov.save(p);
}if(item.equals("Limit")){
lim.save(p);
}
}
}
答案 0 :(得分:4)
创建可保存的界面:
public interface Saveable {
public void save(String p);
}
您的类实现了接口,然后创建了Map:
private Map<String, Saveable> saveMap = new HashMap<>();
用Savable对象填充它,然后根据String调用save方法。
public enum SaveableType {
PRODUCT, COVERAGE, LIMIT
}
public class Controller {
private Product pr = new Product();
private Limit lim = new Limit();
private Coverage cov = new Coverage();
private Map<SaveableType, Saveable> saveableMap = new HashMap<>();
public Controller() {
saveableMap.put(SaveableType.PRODUCT, pr);
saveableMap.put(SaveableType.LIMIT, lim);
saveableMap.put(SaveableType.COVERAGE, cov);
}
// better to use enum for the 2nd parameter not a String
public void save(PolicyData p, String item) {
SaveableType saveables = SaveableType.valueOf(item.toUpperCase());
saveableMap.get(saveables).save(p);
}
}
答案 1 :(得分:1)
不是真正的减少if-else丛林的解决方案。但这可能看起来更“漂亮”。
http://www.w3schools.com/js/js_switch.asp
所以在你的情况下:
switch(item) {
case("Product"): pr.save(item); break;
// and so on...
}
答案 2 :(得分:1)
代码:
gettext