- 策略模式的作用
- 策略模式的与工厂模式的区别(面试有问)
- 策略模式的代码应用
- 策略模式的优缺点
- 策略模式的升级PLUS版本
以上就是本章所有涉及到的知识点
策略模式的作用
定义不同的策略(逻辑),独立封装,然后有一个统一的Context 根据不同的条件,调用不同的策略,用来简化 if else switch 条件判断的。
策略模式的代码应用
import org.springframework.beans.factory.InitializingBean;
public abstract class AbsStrategy implements InitializingBean {
abstract String process(String type);
}
// 第一个策略实现类
@Component
public class FirstStrategy extends AbsStrategy {
@Override
String process(String type) {
return "first";
}
@Override
public void afterPropertiesSet() throws Exception {
StrategyFactory.register("first", this);
}
}
// 第二个策略实现类
@Component
public class TwoStrategy extends AbsStrategy{
@Override
String process(String type) {
return "two";
}
@Override
public void afterPropertiesSet() throws Exception {
StrategyFactory.register("two",this);
}
}
//工厂类管理策略容器
public class StrategyFactory {
private static Map<String,AbsStrategy> strategyMap = new ConcurrentHashMap<>();
public static void register(String type,AbsStrategy absStrategy) {
strategyMap.put(type,absStrategy);
}
public static AbsStrategy getInvokeStrategy(String type) {
return strategyMap.get(type);
}
}
策略模式与工厂模式的区别
策略模式其实是封装不同的行为,通过容器管理,获取不同的策略执行,解偶行为。
工厂模式其实是创建型设计模式,针对不同的类型创建不同的对象,解偶对象。
策略模式的优缺点
优点:逻辑策略可以自由切换,扩展性好,加一个逻辑,只需要增加一个类
缺点:策略类过多,容易造成类爆炸,需要有容器配合维护
策略模式的PLUS版
策略模式在真实应用的过程中,最大的一个矛盾点就是几个简单的逻辑,为了省略if else 引用了太多的类,而且逻辑不能直观的在当前代码体现展示,需要看不同的策略类,所有有了下面的应用方法
@Component
public class StrategyComponent {
private Map<String, Function<String, String>> stringFunctionMap = new HashMap<>();
@Autowired
private ProcessService processService;
@PostConstruct
public void mapInit(){
stringFunctionMap.put("type1", type -> processService.process(type));
stringFunctionMap.put("type2", type -> processService.process2(type));
}
public String apply(String type) {
Function<String, String> function = stringFunctionMap.get(type);
if (function != null) {
return function.apply(type);
}
return "error";
}
}
写在最后,感谢点赞关注收藏转发
欢迎关注我的微信公众号 【猿之村】
来聊聊Java面试
加我的微信进一步交流和学习,微信手动搜索
【codeyuanzhicunup】添加即可
如有相关技术问题欢迎留言探讨,公众号主要用于技术分享,包括常见面试题剖析、以及源码解读、微服务框架、技术热点等。