经验复盘-记一次策略模式的学习和实践

139 阅读3分钟

「Offer 驾到,掘友接招!我正在参与2022春招系列活动-经验复盘,点击查看 征文活动详情

积极响应掘金的文章活动,分享一些实际工作中的实践经验,帮助年轻开发者们学习和思考,是我一直以来都喜欢做的事情,我也很热衷于学习和分享,希望文章内容对你们有所帮助。

我接到了一个开发任务,沟通好具体细节之后,开始开发,大概任务就是对一个数据进行流水操作,分为克隆、打包、构建和发布等操作,你可以想象成对食品的生成和加工和包装等流水线操作。

任务标准是:流水线可变,用户可以根据自己的购买条件来定义流水线

整个业务并不复杂,业务逻辑就是鉴别参数之后,将参数封装好,交给各自的组件处理,问题是如何通知这些组件,这里面涉及到流水通知问题,因此我采用策略模式来处理这些问题,当然你也可以构建非常复杂的Json数据结构,这里就不多提了。

策略模式

策略(Strategy)模式:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

这里我对业务进行了简化,流水通知就是评估后续组件开启还是不开启。

算法封装

算法的封装接口,定义了组件的地址和参数信息

public interface PipelineExcute {
    String doExcute(String url ,String config);
}

构建组件,定义了执行逻辑和执行状态

public class Build implements PipelineExcute {

    @Override
    public String doExcute(String url ,String config) {
        System.out.println("构建处理");
        return "success";
    }
}

克隆组件,定义了执行逻辑和执行状态

public class Clone implements PipelineExcute {
    @Override
    public String doExcute(String url, String config) {
        System.out.println("克隆处理");
        return "success";
    }
}

发布组件,定义了执行逻辑和执行状态

public class Publish implements PipelineExcute {

    @Override
    public String doExcute(String url, String config) {
        System.out.println("发布处理");
        return "success";
    }
}

算法封装上下文

public class PipelineExcuteContext {
    String url;
    String config;
    PipelineExcute excute;

    public PipelineExcuteContext(String url, String config, PipelineExcute excute) {
        this.url = url;
        this.config = config;
        this.excute = excute;
    }

    public String doExcute(){
        System.out.println("查库评估信息");
        String sqlData = "pass";
        if ("pass".equals(sqlData)){
            return excute.doExcute(url,config);
        }
        return "";
   }

    public void doExcuteOne() {
       excute.doExcute(url,config);
    }

代码测试

public static void main(String[] args) {
    String taskName = "build";
    Boolean taskStatus = true;
    String config ="xxx";
    if ("build".equals(taskName) && taskStatus){
        PipelineExcuteContext pipelineExcuteContext = new PipelineExcuteContext("localhost:8081/build", config, new Build());
         pipelineExcuteContext.doExcuteOne();

    }

    if ("publish".equals(taskName) && taskStatus){
        PipelineExcuteContext pipelineExcuteContext = new PipelineExcuteContext("localhost:8082/publish", config, new Publish());
         pipelineExcuteContext.doExcute();

    }

    if ("clone".equals(taskName) && taskStatus){
        PipelineExcuteContext pipelineExcuteContext = new PipelineExcuteContext("localhost:8083/clone", config, new Clone());
        pipelineExcuteContext.doExcute();

    }
}

我们的业务是有一个是必执行的,不管前后怎么样,都必执行。

策略模式总结

  • 我们从中可以看出,策略模式帮助我们简化判断。
  • 当然,我还可以继续往流水线里添加组件,符合开闭原则
  • 把算法的使用和实现进行了分离,用户不用关心组件内部是什么
  • 用户可以根据实际情况,灵活选择

以上就是一个简单的策略模式和业务开发经验复盘,希望可以帮到你们。