我有一个实现如下的方法
public void setAttributes(Data d) {
Model m;
String type = d.getType();
if (type.equals("TYPE1")) {
m.setType(type);
m.setDuration(d.getDuration())
m.setBenefit(d.getBenefit())
m.setPermission(d.getPermission());
} else if (type.equals("TYPE2")) { /* Here we wont be having duration, benefit */
m.setType(type);
m.setLab(true)
}
}
这看起来不可扩展,因为将来如果出现更多类型,那么我们需要继续添加 if else block 。有什么办法可以重构这个吗? 注意:根据类型属性会有所不同。
最佳答案
您可以为每种类型创建一个Data
子类,并使用重写将行为单独附加到每个类。如果您计划拥有非常多的数据类型和大量关联的逻辑,这是有意义的。
public abstract class Data {
...
public abstract void setAttributes(Model m);
}
关于java - 避免java中许多if else语句的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39486188/