Java设计模式之策略模式案例详解

2022-11-13 13:11:00 模式 策略 详解

为什么使用策略模式?

答:策略模式是解决过多if-else (或者switch-case)代码块的方法之一,提高代码的可维护性、可扩展性和可读性。

优缺点

优点

  • 算法可以自由切换(高层屏蔽算法,角色自由切换)。
  • 避免使用多重条件判断(如果算法过多就会出现很多种相同的判断,很难维护)
  • 扩展性好(可自由添加取消算法而不影响整个功能)。

缺点

策略类数量增多(每一个策略类复用性很小,如果需要增加算法,就只能新增类)。所有的策略类都需要对外暴露(使用的人必须了解使用策略,这个就需要其它模式来补充,比如工厂模式、代理模式)。

Spring中哪里使用策略模式

ClassPathXmlApplicationContext Spring 底层Resource接口采用策略模式

Spring 为Resource 接口提供了如下实现类:

  • UrlResource:访问网络资源的实现类。
  • ClassPathResource:访问类加载路径里资源的实现类。
  • FileSystemResource:访问文件系统里资源的实现类。
  • ServletContextResource:访问相对于ServletContext 路径里的资源的实现类
  • InputStreamResource:访问输入流资源的实现类。
  • ByteArrayResource:访问字节数组资源的实现类。

策略模式设计图

  • Strategy::策略接口或者策略抽象类,并且策略执行的接口
  • ConcreateStrategyA、 B、C等:实现策略接口的具体策略类
  • Context::上下文类,持有具体策略类的实例,并负责调用相关的算法

代码案例

统一支付接口

public interface Payment {
    
    String getPayType();
    
    String pay(String order);
}

各种支付方式(策略)

@Component
public class AlipayPayment implements Payment {
    @Override
    public String getPayType() {
        return "alipay";
    }
    @Override
    public String pay(String order) {
        //调用阿里支付
        System.out.println("调用阿里支付");
        return "success";
    }
}
@Component
public class BankCardPayment implements Payment {
    @Override
    public String getPayType() {
        return "bankCard";
    }
    @Override
    public String pay(String order) {
        //调用微信支付
        System.out.println("调用银行卡支付");
        return "success";
    }
}
@Component
public class WxPayment implements Payment {
    @Override
    public String getPayType() {
        return "weixin";
    }
    @Override
    public String pay(String order) {
        //调用微信支付
        System.out.println("调用微信支付");
        return "success";
    }
}

使用工厂模式来创建策略

public class PaymentFactory {
    private static final Map<String, Payment> payStrategies = new HashMap<>();
    static {
        payStrategies.put("weixin", new WxPayment());
        payStrategies.put("alipay", new AlipayPayment());
        payStrategies.put("bankCard", new BankCardPayment());
    }
    public static Payment getPayment(String payType) {
        if (payType == null) {
            throw new IllegalArgumentException("pay type is empty.");
        }
        if (!payStrategies.containsKey(payType)) {
            throw new IllegalArgumentException("pay type not supported.");
        }
        return payStrategies.get(payType);
    }
}

测试

public class Test {
    public static void main(String[] args) {
        String payType = "weixin";
        Payment payment = PaymentFactory.getPayment(payType);
        String pay = payment.pay("");
        System.out.println(pay);
    }
}

到此这篇关于Java设计模式之策略模式详解的文章就介绍到这了,更多相关Java策略模式内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章