springboot服务使用策略模式

springboot服务使用策略模式,第1张

1、前言

实际开发过程中,会进行大量的if else判断,这使得我们的代码非常臃肿且可读性较差。策略模式能够帮助我们很好的解决这个问题。下面以一个简单的例子说明如何在sprinboot项目中使用策略模式。

2、消息发送策略模式搭建 2.1、定义一个消息发送接口
public interface MsgSend {

    void sendMessage();
}
2.2、定义短信消息发送逻辑
//shortMsgSendService表示以该名字注入bean
@Service("shortMsgSendService")
public class ShortMsgSendService implements MsgSend {
    @Override
    public void sendMessage() {
        //发送逻辑
        System.out.println("发送短信消息");
    }
}
2.3、定义微信消息发送逻辑
//表示以wxMsgSendService名称注入bean
@Service("wxMsgSendService")
public class WxMsgSendService implements MsgSend {
    @Override
    public void sendMessage() {
        //发送逻辑
        System.out.println("发送微信模板消息");
    }
}
2.4、定义策略类
@Service
public class MsgSendStrategy {

    //@Resource默认会以名称进行注入
    @Resource
    private ShortMsgSendService shortMsgSendService;

    @Resource
    private WxMsgSendService wxMsgSendService;

    //配置文件定义使用哪种策略
    @Value("${local.sendType}")
    private String sendType;

    public MsgSend getMsgSendType(){
        if ("1".equals(sendType)){
            return shortMsgSendService;
        }else{
            return wxMsgSendService;
        }
    }
}
2.5、在application.yml文件中添加配置
local:
  sendType: 2

完成上述步骤,策略模式就写完了,下面进行测试

2.6、测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = QuickApplication.class)
public class MyTest extends AbstractJUnit4SpringContextTests {


    @Resource
    private MsgSendStrategy msgSendStrategy;

    @Test
    public void zegTest01(){
        MsgSend msgSendType = msgSendStrategy.getMsgSendType();
        msgSendType.sendMessage();
        //当配置文件为1时,输出发送短信消息
        //当配置文件为2时,输出发送微信模板消息
    }
}
3、结语

本例已经测试过,没有什么问题,如果大家有更好的想法,希望留言指正。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/877868.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存