在开发中,一旦业务逻辑复杂的时候,我们难免会使用大量的if,else,但是,那么如何对相应的if,else进行一个优化,来提高我们项目的可阅读性呢?
1、去掉不需要的if,else
2、将if,else模块化处理
3、必要时,采用责任链模式;
一、去掉多余的if,else:
有人可能会问,尼玛,如果是多余的,我特么还会写吗?你说,去掉多余的if,else这不是废话嘛。=_=,嗯,确实也是这个道理。别打我,我慢慢说;
1、首先我们思考一下,产生if,else的原因是什么?
肯定是数据源不确定,从而我们通过判断具体的标识,来确定相应的数据源;这么说比较抽象,下面举一个例子;
我们出行可以使用公交,地铁,计辰车之类的,每种出行方式都有自己独特的计算方式;我们通过传入相应的标识,我们就可以得到具体的价格,图如下:
我们用代码实现就是如下;
public class PriceCalculator {
//**具体的标识**
private static final int BUS=1;
private static final int SUBWAY=2;
private static final int taxi=3;
public static void main(String[] args) {
PriceCalculator calculator=new PriceCalculator();
//**通过判断标识来决定相应的数据源;**
System.out.println("坐16公里的公交车票价为:"+calculator.calculatePrivce(10,BUS));
}
//**这里就是我们需要改良的相应的if,else,其实是没有必要的;**
public int calculatePrivce(int km,int type) {
if(type==BUS){
return busPrice(km);
}else if(type==taxi) {
return 3;
}else {
return subwayPrice(km);
}
}
/**
* 公交车的价格
* @return
*/
private int busPrice(int km) {
}
/**
* 地铁的价格
* @return
*/
private int subwayPrice(int km) {
}
}
这里我们其实如果交通工具过多的话,在calculatePrivce里面其实是有大量的if,else代码的;不仅阅读性难,而且扩展极其困难;
这里我们的优化方案如下图:
具体的代码如下:
//抽象的交通工具;
public interface CalculateStrategy {
public int calculate(int km);
}
//具体的交通工具;
public class Subway implements CalculateStrategy {
@Override
public int calculate(int km) {
// TODO Auto-generated method stub
return 0;
}
}
//计算费用的类
public class PriceCalculator2 {
//抽象的交通工具
CalculateStrategy mCalculateStrategy;
public CalculateStrategy getmCalculateStrategy() {
return mCalculateStrategy;
}
public void setCalculateStrategy(CalculateStrategy mCalculateStrategy) {
this.mCalculateStrategy = mCalculateStrategy;
}
public int calculate(int km) {
return mCalculateStrategy.calculate(km);
}
}
public static void main(String[] args) {
PriceCalculator2 calculator= new PriceCalculator2();
calculator.setCalculateStrategy(new Subway());//这里Subway也是和bus一样实现了抽象的交通工具
System.out.println("坐16公里的地铁票价为:"+calculator.calculate(16));
}
通过上面的代码,是不是就将判断交通工具的唯一标识给去掉了呢?是不是于此同时去掉了大量的if,else的判断方法呢?
本部分内容参考:《android源码分析与设计模式》—策略模式