一个类的行为或其算法可以在运行时更改,我们把它降维到代码层面。 用人话翻译一下就是,运行时我给你这个类的方法传不同的“key”,你这个方法会执行不同的业务逻辑。 细品一下,这不就是 if else 干的事吗?
但是也存在缺点
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class StrategyTest {
public static void main(String[] args) {
StrategyProvider provider = new StrategyProvider();
StrategyA strategyA = new StrategyA();
StrategyB strategyB = new StrategyB();
provider.strategyList.add(strategyA);
provider.strategyList.add(strategyB);
provider.excute("A");
provider.excute("B");
provider.excute("C");
}
}
class StrategyProvider {
//SpringBoot里面可以直接注入
List<IStrategy> strategyList = new ArrayList<>();
public void excute(String str) {
Optional<IStrategy> strategy = strategyList.stream().filter(x -> x.judge(str)).findFirst();
if (strategy.isPresent()) {
strategy.get().process(str);
}
}
}
interface IStrategy {
boolean judge(String str);
void process(String str);
}
class StrategyA implements IStrategy {
@Override
public boolean judge(String str) {
if (Objects.equals("A", str)) {
return true;
}
return false;
}
@Override
public void process(String str) {
System.out.println(str);
}
}
class StrategyB implements IStrategy {
@Override
public boolean judge(String str) {
if (Objects.equals("B", str)) {
return true;
}
return false;
}
@Override
public void process(String str) {
System.out.println(str);
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
public class MapStrategy {
public static void main(String[] args) {
Map<String, Function<String, String>> strategyMap = new HashMap<>();
//在SpringBoot里面可以在初始化时候就加入
strategyMap.put("A", e -> e + "处理了A");
strategyMap.put("B", e -> e + "处理了B");
Function<String, String> functionA = strategyMap.get("A");
Function<String, String> functionB = strategyMap.get("B");
Function<String, String> functionC = strategyMap.get("C");
if (Objects.nonNull(functionA)) {
System.out.println(functionA.apply("A"));
}
if (Objects.nonNull(functionB)) {
System.out.println(functionA.apply("B"));
}
if (Objects.nonNull(functionC)) {
System.out.println(functionA.apply("C"));
}
}
}