在代码中使用过多的if else进行逻辑判断比较影响阅读,更重要的是,如果增加或减少一种逻辑情况就需要修改if else的分支,维护性差。
if(type == 1) do1()
else if(type == 2) do2()
else...
if else逻辑两个关键点:1、是什么条件;2、做什么事
策略模式是通过接口抽象这一系列动作,提供统一的行为模式。用来解决做什么事。
map用来f封装条件,根据条件不同选择不同的实现类赋予接口。用来解决是什么条件。
那么上面那段代码可以变为:
// 抽象动作
interface do{ do(); }
class do1 implement do { do1() } // 实现do1
class do2 implement do { do2() } // 实现do2
// 封装条件
Map con = new HashMap
con.put(1, new do1())
con.put(2, new do2())
// 逻辑调用变为
do do = con.get(type);
do.do();
或者更完美一点可以结合下工厂模式:
doFactory {
private static Map con = new HashMap();
static {
con.put(1, new do1());
con.put(2, new do2());
}
public static do creator(type){
return con.get(type);
}
}
// 逻辑调用变为
do do = doFactory.creator(type);
do.do();