JAVA程序经常看到一个函数中包含了十几个if-else的分支判断
比如 根据不同职位增加工资的例子
-
public class Employee {
-
private int salary = 10;
-
-
public void addMoney(String str) {
-
if ("初级JAVA程序员".equals(str)) {
-
this.salary = salary + 30;
-
} else if ("中级JAVA程序员".equals(str)) {
-
this.salary = salary + 50;
-
} else if ("高级JAVA程序员".equals(str)) {
-
this.salary = salary + 80;
-
} else if ("架构师".equals(str)) {
-
this.salary = salary + 100;
-
} else if ("数据库管理员".equals(str)) {
-
this.salary = salary + 100;
-
} else if ("项目经理".equals(str)) {
-
this.salary = salary + 100;
-
} else if ("菜鸟".equals(str)) {
-
this.salary = salary + 10;
-
}
-
// ...
-
System.out.println(this.salary);
-
}
-
-
public static void main(String[] args) {
-
Employee e = new Employee();
-
e.addMoney("菜鸟");
-
}
-
}
可以改写如下
-
import java.util.HashMap;
-
import java.util.Map;
-
-
public class Employee {
-
private int salary = 10;
-
-
private interface IStrategy {
-
int addMoney();
-
};
-
-
Map<String, IStrategy> strategy = new HashMap<String, IStrategy>();
-
-
{
-
strategy.put("初级JAVA程序员", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 30;
-
}
-
});
-
-
strategy.put("中级JAVA程序员", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 50;
-
}
-
});
-
-
strategy.put("高级JAVA程序员", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 80;
-
}
-
});
-
-
strategy.put("架构师", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 100;
-
}
-
});
-
-
strategy.put("数据库管理员", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 100;
-
}
-
});
-
-
strategy.put("项目经理", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 100;
-
}
-
});
-
-
strategy.put("菜鸟", new IStrategy() {
-
@Override
-
public int addMoney() {
-
return 10;
-
}
-
});
-
-
}
-
-
public void addMoney(String str) {
-
this.salary = salary + strategy.get(str).addMoney();
-
System.out.println(this.salary);
-
}
-
-
public static void main(String[] args) {
-
Employee e = new Employee();
-
e.addMoney("菜鸟");
-
}
-
}
如果是复杂的项目,可以把匿名内部类改为普通类.
改写之后,无论新增或者删除逻辑,都非常的简单明了,并且逻辑的变更,限制在了一个较小的范围.
实现了高内聚,低耦合的设计思路.
参考:
http://raychase.iteye.com/blog/1814187
过多if-else分支的优化
原文:http://blog.itpub.net/29254281/viewspace-1409748/