前言
当代码中出现多重if-else
语句或者switch
语句时。弊端之一:如果这样的代码出现在多处,那么一旦出现需求变更,就需要把所有地方的if-else
或者switch
代码进行更改,要是遗漏了某一处,那么程序就会出错。弊端之二:代码逻辑难以理解。
卫语句
卫语句的使用,并不能改变前言说的弊端:一旦需求更改,需要修改所有使用更改需求的if-else
代码块。不过使用卫语句可以让自己或者代码维护人员很容易的了解代码的含义。
代替异常分支
所谓的异常分支就是普通情况之外的分支,这种情况的下的if-else
可以用
if (condition)
return obj;
代替。
代替多重if-else
分支
这个情况的代替方式是可以为
if (isSunshine()) {
// 晴天时处理逻辑
}
if (isRain()) {
// 下雨时处理逻辑
}
if (isOvercast()) {
// 阴天时处理逻辑
}
...
策略模式
使用策略模式可以代替多重if-else
和switch
语句,让代码维护变得更加简单。
策略模式UML:
- 环境(Context)角色:持有一个Strategy的引用
- 抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现
- 具体策略(ConcreteStrategy)角色:包装了相关的算法或行为
策略模式代码模板:
package xyz.zeling.test.strategy.template;
import xyz.zeling.test.strategy.template.base.Strategy;
/**
* @description 环境角色
* @author zeling
* @date 2018年1月14日 下午8:43:58
*/
public class Context {
/**
* 策略对象
*/
private Strategy strategy;
/**
* @param strategy 具体策略对象
*/
public Context(Strategy strategy) {
this.strategy = strategy;
}
/**
* @description 执行策略方法
* @date 2018年1月14日 下午8:43:31
*/
public void contextInterface() {
strategy.strategyInterface();
}
}
package xyz.zeling.test.strategy.template.base;
/**
* @description 抽象策略角色
* @author zeling
* @date 2018年1月14日 下午8:41:14
*/
public interface Strategy {
/**
* @description 策略方法
* @date 2018年1月14日 下午8:41:00
*/
void strategyInterface();
}
package xyz.zeling.test.strategy.template;
import xyz.zeling.test.strategy.template.base.Strategy;
/**
* @description 具体策略类A
* @author zeling
* @date 2018年1月14日 下午8:45:00
*/
public class ConcreteStrategyA implements Strategy {
@Override
public void strategyInterface() {
// TODO Auto-generated method stub
}
}
package xyz.zeling.test.strategy.template;
import xyz.zeling.test.strategy.template.base.Strategy;
/**
*