策略模式PLUS

11 篇文章 0 订阅
  • 策略模式的作用
  • 策略模式的与工厂模式的区别(面试有问)
  • 策略模式的代码应用
  • 策略模式的优缺点
  • 策略模式的升级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】添加即可
如有相关技术问题欢迎留言探讨,公众号主要用于技术分享,包括常见面试题剖析、以及源码解读、微服务框架、技术热点等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值