Java使用策略模式替换掉 if else

Java使用策略模式替换掉 if else

我们的代码中常常大量的使用 if else ,如果条件在不断的增加,我们就需要继续在后面增加if else,代码就会越来越臃肿,可读性差,后期非常不好维护,下面给大家分享一下策略模式的使用。

什么是策略模式

策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

下面就以发送消息为例,在不同的业务场景我们需要给客户发送不同的消息。

定义抽象策略

/**
 * 发送消息接口
 */
public interface SendService {
          
   

    /**
     * 发送短信
     * @param msg
     * @return
     */
    String sendMessage(String msg);
}

分别定义不同的实现方法

购买成功发送消息

/**
 * 购买成功发送短信
 */
@Service("bug")
public class BuyServiceImpl implements SendService {
          
   


    /**
     * 购买成功发送短信
     *
     * @param msg
     * @return
     */
    @Override
    public String sendMessage(String msg) {
          
   
        return "购买成功";
    }
}

发货通知发送消息

/**
 * 发货通知短信
 */
@Service("deliver")
public class DeliverServiceImpl implements SendService {
          
   


    /**
     * 发货发送短信
     *
     * @param msg
     * @return
     */
    @Override
    public String sendMessage(String msg) {
          
   
        return "发货成功";
    }
}

退货成功发送短信

/**
 * 退货通知
 */
@Service("refund")
public class RefundServiceImpl implements SendService {
          
   


    /**
     * 退货发送短信
     *
     * @param msg
     * @return
     */
    @Override
    public String sendMessage(String msg) {
          
   
        return "退货成功";
    }
}

使用策略模式发送短信

在不用的发送短信类中我们通过@Service注解我们把所有实现类放入到bean容器中,在发送短信的时候我们可以直接从容器中拿到我们所需要的的类

@Autowired
    private ApplicationContext applicationContext;

    /**
     * 使用策略模式发送短信
     *
     * @param type  发送短信类型
     * @param context 发送内容
     * @return
     */
    @GetMapping("msg")
    public String sendMsg(@RequestParam("type") String type, @RequestParam("context") String context) {
          
   
        SendService service = applicationContext.getBean(type, SendService.class);
        String result = service.sendMessage(context);
        return result;
    }

测试结果

通过type来决定发送不同的消息

对比一下if else

使用if else 如果我们有N个发送类型我们就需要N个if else 就要继续在后面增加代码

/**
     * 使用if  else
     *
     * @param type
     * @param context
     * @return
     */
    @GetMapping("msg")
    public String sendMsgEnd(@RequestParam("type") String type, @RequestParam("context") String context) {
          
   
        if ("bug".equals(type)) {
          
   
            // 发送购买短信
        } else if ("deliver".equals(type)) {
          
   
            // 发送发货短信
        } else if ("refund".equals(type)) {
          
   
            // 发送退货短信
        }

        return "";
    }
经验分享 程序员 微信小程序 职场和发展