使用策略模式优化if-else代码

基于Spring使用 策略模式 优化if-else重复代码,降低代码的重复性,增加代码拓展性。

1、接口

/**
 * 支付接口
 *
 * @author 逆行
 * @date 2024/05/10 15:52
 **/
public interface IPay
{
    boolean match(String type);

    void pay();
}

2、实现类

import org.springframework.stereotype.Service;

/**
 * 微信支付
 *
 * @author 逆行
 * @date 2024/05/10 15:52
 **/
@Service
public class WxPay implements IPay
{
    @Override
    public boolean match(String type)
    {
        return "wx".equals(type);
    }

    @Override
    public void pay()
    {
        System.out.println("微信支付");
    }
}
import org.springframework.stereotype.Service;

/**
 * 支付宝支付
 *
 * @author 逆行
 * @date 2024/05/10 15:52
 **/
@Service
public class ZfbPay implements IPay
{
    @Override
    public boolean match(String type)
    {
        return "zfb".equals(type);
    }

    @Override
    public void pay()
    {
        System.out.println("支付宝支付");
    }
}

3、使用

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 支付web层
 *
 * @author 逆行
 * @date 2024/05/10 15:54
 **/
@RestController
public class PayController
{
    @Autowired
    private List<IPay> payList;

    @PostMapping("/doPay")
    public void doPay(String type)
    {
        for (IPay pay : payList)
        {
            if (pay.match(type))
            {
                pay.pay();
                break;
            }
        }
    }
}