示例
日常开发中,遇到判断分支的时候,if-else 是我们的首选方式,如下:
public class Before {
public static void main(String[] args) {
int type = 8;
if (type == 0) {
System.out.println("类型为0");
} else if (type == 1) {
System.out.println("类型为1");
} else if (type == 2) {
System.out.println("类型为2");
} else if (type == 3) {
System.out.println("类型为3");
} else if (type == 4) {
System.out.println("类型为4");
} else if (type == 5) {
System.out.println("类型为5");
} else if (type == 6) {
System.out.println("类型为6");
} else if (type == 7) {
System.out.println("类型为7");
} else if (type == 8) {
System.out.println("类型为8");
} else if (type == 9) {
System.out.println("类型为9");
} else {
System.out.println("其他类型");
}
}
}
上面的例子一看就知道问题了,一个简单的判断导致代码变的很长,可阅读性降低,维护性降低,看起来一点都不专业!
重构后
原来的十几行代码只需要两行就可以搞定了
public class After {
public static void main(String[] args) {
Context context = new Context(new Type1());
context.execute();
}
}
原理
请看第一行代码的构造器里面穿了一个参数:new Type1(),他就相当于之前的代码里面的 type == 1
如果我现在要判断 type == 2,直接 new Type2() 作为 Context 构造器的参数即可,充分利用多态性减少代码量,那么完整的代码怎么写呢?
源代码
项目结构
直接看优化后的代码吧,Type 类是一个抽象类,定义基本的操作
Type.java
public abstract class Type {
public abstract void outPut();
}
impl 包里面是它的实现类
Type0.java Type1.java
public class Type0 extends Type {
@Override
public void outPut() {
System.out.println("类型为0");
}
}
public class Type1 extends Type {
@Override
public void outPut() {
System.out.println("类型为1");
}
}
Context 类是用来连接上下文的
Context.java
public class Context {
private Type type;
public Context(Type type) {
this.type = type;
}
public void execute() {
type.outPut();
}
}
After.Java 是主类
public class After {
public static void main(String[] args) {
Context context = new Context(new Type1());
context.execute();
}
}
进一步解释
当我想判断 type == 3 的时候,也就是想再写一个 else 的时候,直接写一个 Type3.java 然后继承 Type 重写他的方法,然后往 Context 的构造器里面 new Type3() 即可
Context context = new Context(new Type3());
看起来貌似不合理,没有 if-else 的灵魂,但是你仔细想一想,我们用 if-else 来做判断的时候,不就是因为我们已经知道传入的参数是什么了,然后需要它匹配一条路径出去吗?这里的道理也是一样,你知道自己需要 new 一个什么类型的 Type 进去,然后代码从哪里出去,由多态性去帮你实现!
总结
策略模式实现的 if-else 是基于多态实现的
当需要添加 else 的时候其实就是改变 Context() 构造器里面的传入的 Type 类型
就这么简单!
.