初识Spring Cloud系列——Spring Boot篇06|Java 开发实战 | 周末学习

image.png
这是我参与更文挑战的第6天,活动详情查看: 更文挑战

本文正在参加「Java主题月 – Java 开发实战」,详情查看 活动链接

本文已参与周末学习计划,点击查看详情

时间过的真快,本想着周末能把Spring Boot中的设计模式都学习完,没想到理想很丰满,现实有点骨感,目前设计模式以及了解了一般,还剩小半,加油。
活继续肝下去,今天看看策略模式

策略模式 Strategy Pattern

意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。

何为策略模式?

策略,指计策;谋略。一般是指:1. 可以实现目标的方案集合;2. 根据形势发展而制定的行动方针和斗争方法;3. 有斗争艺术,能注意方式方法。(此处来自某科的对于“策略”一词解释:)

实现目标的方案集合:这种解释我觉得也可以用在策略模式上,比如:
计算器的多种运算规则的集合
旅游时,各种出行方式(徒步、骑行、做车、或者通过媒体,目光随着“天问一号”来一场火星视觉之旅)的选择

场景实现

当商店给小明或小雪发衬衫的时候,物流的选择方案也是一种策略,店家首先要考虑的就是物流的运费问题,
借用下上一篇文章(初识Spring Cloud系列——Spring Boot篇05|Java 开发实战)的图
image.png

以下代码,来看看选择各种物流的费用的策略

public class StrategyPatternDemo {

    public static void main(String[] args) {
        Context context = new Context(new Sf_express());
        System.out.println("使用sf快递运费" + context.executeStrategy(0.5) + "元");

        context = new Context(new Jingdong_express());
        System.out.println("使用jd快递运费" + context.executeStrategy(0.5) + "元");

        context = new Context(new Correo_express());
        System.out.println("使用yz快递运费" + context.executeStrategy(0.5) + "元");
    }
}

//创建物流花费接口
interface Strategy {
    public double cost(double weight);
}
//具体物流花费计算的实现
class Sf_express implements Strategy{
    @Override
    public double cost(double weight) {
        return 12 + weight*2;
    }
}
//具体物流花费计算的实现
class Jingdong_express implements Strategy{
    @Override
    public double cost(double weight) {
        return 6 + weight*2;
    }
}
//具体物流花费计算的实现
class Correo_express implements Strategy{
    @Override
    public double cost(double weight) {
        return 6 + weight*1;
    }
}
//创建一个使用某种策略的类Context
class Context {
    private Strategy strategy;

    public Context(Strategy strategy){
        this.strategy = strategy;
    }

    public double executeStrategy(double weight){
        return strategy.cost(weight);
    }

复制代码

结果如下:
image.png

策略模式在Spring中的应用

在Spring中,实例化对象的时候用到了Strategy模式

image.png

InstantiationStrategy为抽象接口
SimpleInstantiationStrategy实现接口,但是在方法instantiate中进行判断,针对bd中没有MethodOverrides的,直接通过jdk反射进行构造函数调用
image.png

针对有需要针对方法做MethodOverrides的,则可以通过另一种方式处理,在SimpleInstantiationStrategy中是通过:instantiateWithMethodInjection()方法处理的,在CglibSubclassingInstantiationStrategy中对该方法做了override实现。

image.png

今日小结

策略模式搞定,勉强能学到一些,从简单的应用场景,再到场景的实现,以及策略模式在Spring中实例化对象的使用,但是实例化对象过程还是有点模糊,这点有待加强。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享