使用策略模式优化if else
有这样一段逻辑
function{ | |
for{ | |
if() | |
if() | |
if( | |
if( | |
) | |
) | |
... | |
} | |
} |
公司有的祖传的代码,是一段规则校验,校验的越多,每一个请求都会进来校验,加上后来的开发人员也不注意,每次多加校验就多加一个if,只要命中就在if里面写逻辑,好一点的会抽到一个方法中,看起来稍好些,但是if越加越多,一个循环最终发展到了数千行,可读性越来越差,领导点名重构;
解决方案: 策略模式+工厂模式
工厂模式大家都很熟悉了,所以简单介绍一下策略模式
策略模式,顾名思义,组要是依靠策略来完成类的具体行为,所以,策略模式的核心就是编写不同的策略类,我们可以通过Java的接口编写抽象策略,用不同的实现类来完成策略,当然策略模式还需要一个上下文的类,用来选择策略;现实生活中也有很好的例子,例如支付方式,你可以选择微信支付,支付宝支付,银行卡支付等,
首先我们编写抽象策略
public interface Strategy { | |
Boolean check(Object obj); | |
} |
然后我们编写具体的实现
public class StrategyImpl01 implements Strategy{ | |
@Override | |
public int check(Object obj) { | |
// 实现具体的业务逻辑 | |
return ""; | |
} | |
} | |
public class StrategyImpl02 implements Strategy{} | |
public class StrategyImpl03 implements Strategy{} | |
... |
实现上下文类
public class Context { | |
private Strategy strategy; | |
public Context(Strategy strategy){ | |
this.strategy = strategy; | |
} | |
public int executeStrategy(Object obj){ | |
return strategy.check(obj); | |
} | |
} |
调用策略类
public static void main(String[] args) { | |
Context context = new Context(new StrategyImpl01()); | |
context.check(obj) | |
context = new Context(new StrategyImpl02()); | |
context.check(obj) | |
context = new Context(new StrategyImpl03()); | |
context.check(obj) | |
} |
到此,策略模式已经实现了,但是不是特别优雅,所以我们加上了工厂模式
编写策略工厂
public clss Factory{ | |
// 申明一个全局的map,key 为if中的条件,value为策略类 | |
private static final Map<String,Strategy> strategyMap = new HashMa<String,Strategy>(); | |
// 填充map | |
static { | |
strategyMap.put("aaa",new StrategyImpl01()) | |
strategyMap.put("bbb",new StrategyImpl02()) | |
strategyMap.put("bbb",new StrategyImpl03()) | |
... | |
} | |
// 暴露一个获取map的方法 | |
public static Strategy getStrategy(String key){ | |
return strategyMap.get(key).check(obj) | |
} | |
} |
这样,我们只需要在用的时候
public static void main(String[] args){ | |
Factory.getStrategy(key); | |
} |
TYPESCRIPT 复制 全屏
看起来优雅多了