if (variable == value1) {
// 业务逻辑1
} else if (variable == value2) {
// 业务逻辑2
} else {
// 业务逻辑3
}
存在的问题:
switch (variable) {
case value1:
commonDoSomething();
doSomething1();
break;
case value2:
commonDoSomething();
doSomething2();
break;
default:
commonDoSomething();
doSomething3();
break;
}
改进:
存在的问题:
public interface Animal {
void makeSound();
}
public class Dog implements Animal {
public void makeSound() {
System.out.println("业务逻辑1");
}
}
public class Cat implements Animal {
public void makeSound() {
System.out.println("业务逻辑2");
}
}
public class Main {
public static void main(String[] args) {
Animal animalDog = new Dog();
animalDog.makeSound();
Animal animalCat = new Cat();
animalCat.makeSound();
}
}
改进:
存在的问题:
public interface Strategy {
void doSomething();
}
public class StrategyA implements Strategy {
public void doSomething() {
//业务逻辑1
}
}
public class StrategyB implements Strategy {
public void doSomething() {
//业务逻辑2
}
}
public class Main {
public static void main(String[] args) {
Strategy strategy = getStrategy();
strategy.doSomething();
}
}
改进:
使用策略模式,可以发现策略模式和多态其实也没有多大的区别,但关键就在于getStrategy()方法,它的实现的多变,可以大大提高代码的可扩展性,无需修改了核心代码
public GetStrategy {
private static final Map<String, Strategy> map = new HashMap(){{
put("StrategyA", new StrategyA());
put("StrategyB", new StrategyB());
}};//双花括号表示一个类继承HashMap类并重写其构造方法
public Strategy getStrategy(String strategyName) {
return map.get(strategyName);
};
}
实现:
1.将所有的策略中存储在一个Map中,这样当我们需要增加逻辑时只需要增加一个put即可,代码可扩展性很强,而且getStrategy()里面的代码和使用getStrategy()方法的核心逻辑都无需修改。
2.策略名可以在最开始的配置代码中传入,如配置类中就传入
存在的问题
如果是复杂的逻辑来决定需要选取的策略,而不是通过策略名来选取的话,就无法实现,如果要实现的话需要增加一个策略匹配器,如下:
public interface Matcher {
public String match() {
//判断逻辑,返回策略名
}
}
//使用
public class Main {
public static void main(String[] args) {
Strategy strategy = getStrategy(new MatcherImpl().match());
strategy.doSomething();
}
}
优缺点:
class MatcherChain {
private List<Matcher> matcherList = new ArrayList(){{
add(new MatcherA());
add(new MatcherB());
}};
public String match() {
for (Matcher matcher : matcherList) {
String strategyName = matcher.match()
if (strategyName != null) {
return strategyName;
}
}
}
}