美文网首页程序员
java设计模式-策略模式

java设计模式-策略模式

作者: l只为终点 | 来源:发表于2020-05-15 16:58 被阅读0次

    策略模式(Strategy Pattern)也叫做政策模式(Policy Pattern),是一种行为型模式。

    一、定义

    ​ Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

    定义一系列的算法家族,分别封装起来,并且让他们之间可以互相替换,算法可以独立的变化而不会影响用户的使用。

    二、应用

    1. 应用场景

    策略模式在生活中的应用非常多,比如互联网支付,每次下单的时候支付方式会有很多,如支付宝、微信、银联等。再比如地图导航设计,有轿车导航、货车导航、自行车导航、步行导航等,还有像我们的商品促销打折活动等等,都可以使用策略模式去实现。

    策略模式可以解决在同一个业务有很多不同的算法处理情况下,使用if...else或者swich...case所带来程序的复杂性和臃肿性。

    在我们实际开发中大概有以下几种情况使用策略模式:

    • 当我们要在对象中使用算法的不同变体,并希望在运行时可以从一种算法切换到另外一种算法
    • 当我们有很多类似的类,它们只是在执行某些行为方式的不同时
    • 需要将一些业务的实现逻辑和算法的实现细节隔离开,并且该实现细节在逻辑的上下文中并不那么重要时
    1. 角色:
      • Context(上下文):用来操作策略的上下文环境,维护对具体策略的引用,并且近通过策略接口于此对象通信,封装可能存在的变化。

      • Strategy(抽象策略):策略接口对所有的策略都是通用的,规定策略或者算法的行为。

      • ConcreteStrategy(具体策略):具体策略实现了上下文使用的算法的不同策略或者算法的行为。

      • Client(客户端):客户端创建一个特定的策略传递给上下文,上下文需要提供一个设置策略的方法,允许客户端在运行时动态更换策略。

    策略模式中的上下文环境,主要是为了隔离用户端与具体策略类的耦合,让客户端只与上下文环境沟通,无需关注具体策略的实现。

    1. 类图:
    屏幕快照 2020-05-15 12.21.19.png
    1. 例子:

    我们还是用大家耳熟能详的支付过程作为案例,首先我们简单的看下整体类图:


    AliPay.png

    首先创建一个支付策略接口PaymentStrategy(当然此处也可以是抽象类),定义一个支付名称接口和一个支付接口:

    package com.laozhao.pattern.strategy.payment;
    
    public interface PaymentStrategy {
    
      public String getPaymentName();
    
      public boolean doPay(double money);
    }
    

    然后分别实现3个具体策略,AliPay、WechatPay和UnionPay:

    package com.laozhao.pattern.strategy.payment;
    
    public class AliPay implements PaymentStrategy {
    
      @Override
      public String getPaymentName() {
        return "支付宝";
      }
    
      @Override
      public boolean doPay(double money) {
        System.out.println("支付宝支付" + money + "成功");
        return true;
      }
    
    }
    
    package com.laozhao.pattern.strategy.payment;
    
    public class WechatPay implements PaymentStrategy {
    
      @Override
      public String getPaymentName() {
        return "微信支付";
      }
    
      @Override
      public boolean doPay(double money) {
        System.out.println("微信支付" + money + "成功");
        return true;
      }
    
    }
    
    package com.laozhao.pattern.strategy.payment;
    
    public class UnionPay implements PaymentStrategy {
    
      @Override
      public String getPaymentName() {
        return "银联支付";
      }
    
      @Override
      public boolean doPay(double money) {
        System.out.println("银联支付" + money + "成功");
        return true;
      }
    
    }
    

    创建一个支付策略上下文:

    package com.laozhao.pattern.strategy.payment;
    
    public class PaymentContext {
    
      public static final String ALI_PAY = "AliPay";
      public static final String WECHAT_PAY = "WechatPay";
      public static final String UNION_PAY = "UnionPay";
    
      public static PaymentStrategy getPayment(String type) {
        if (type == null || type.trim().length() == 0) {
          return new AliPay();
        }
        switch (type) {
          case ALI_PAY:
            return new AliPay();
          case WECHAT_PAY:
            return new WechatPay();
          case UNION_PAY:
            return new UnionPay();
          default:
            return new AliPay();
        }
      }
    
    }
    

    创建测试类:

    package com.laozhao.pattern.strategy.payment;
    
    public class StrategyTest {
    
      public static void main(String[] args) {
        String aliPay = PaymentContext.ALI_PAY;
        PaymentStrategy payment = PaymentContext.getPayment(aliPay);
        System.out.println("支付类型:" + payment.getPaymentName());
        payment.doPay(300);
      }
    
    }
    

    运行结果输出:

    支付名称: 支付宝
    支付宝支付300.0成功
    

    三、和工厂模式配合使用

    ​ 上面的代码看起来整体已经解耦多了,但是经过一段时间的业务积累,我们可能需要加入其它的支付方式,比如京东支付、苹果支付等,这个时候我们会继续追加switch...case选项,看起来代码又需要优化了,此时我们考虑到使用工厂模式进行优化,对上面的PaymentContext类进行优化如下:

    package com.laozhao.pattern.strategy.paymentfactory;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class PaymentContext {
    
      public static final String ALI_PAY = "AliPay";
      public static final String WECHAT_PAY = "WechatPay";
      public static final String UNION_PAY = "UnionPay";
    
      private static Map<String, PaymentStrategy> strategyMap = new HashMap<>();
      private static PaymentStrategy defaultPay = new AliPay();
    
      static {
        strategyMap.put(ALI_PAY, new AliPay());
        strategyMap.put(WECHAT_PAY, new WechatPay());
        strategyMap.put(UNION_PAY, new UnionPay());
      }
    
      public static PaymentStrategy getPayment(String type) {
        PaymentStrategy strategy = strategyMap.get(type);
        return strategy == null ? defaultPay : strategy;
      }
    
    }
    

    至此我们只需要维护strategyMap中的策略类,并通过工厂模式来取出其中的策略。

    四、在源码中的体现

    1. java.util.Comparator#compare() jdk中的Comparator接口中的compare方法我们用的比较多,经常用来做数组或者列表的排序,此处定义了一个抽象的策略接口:
    @FunctionalInterface
    public interface Comparator<T> {
        
        int compare(T o1, T o2);
        ...
    }
    

    接口下有很多的实现类,我们也会把Comparator作为参数传入作为排序策略,例如Collections#sort()

    public class Collections {
    ...
        public static <T> void sort(List<T> list, Comparator<? super T> c) {
        list.sort(c);
        }
    ...
    }
    

    再比如Arrays#parallelSort()

    public class Arrays {
    ...
        public static <T> void parallelSort(T[] a, Comparator<? super T> cmp) {
            if (cmp == null)
                cmp = NaturalOrder.INSTANCE;
            int n = a.length, p, g;
            if (n <= MIN_ARRAY_SORT_GRAN ||
                (p = ForkJoinPool.getCommonPoolParallelism()) == 1)
                TimSort.sort(a, 0, n, cmp, null, 0, 0);
            else
                new ArraysParallelSortHelpers.FJObject.Sorter<T>
                    (null, a,
                     (T[])Array.newInstance(a.getClass().getComponentType(), n),
                     0, n, 0, ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?
                     MIN_ARRAY_SORT_GRAN : g, cmp).invoke();
        }
    ...
    }
    
    1. javax.servlet.http.HttpServlet:
    public abstract class HttpServlet extends GenericServlet {
      
       protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
         ...
        }
     
       protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
            String protocol = req.getProtocol();
            String msg = lStrings.getString("http.method_get_not_supported");
            if (protocol.endsWith("1.1")) {
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            }
        }
     
        protected void doPut(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
            String protocol = req.getProtocol();
            String msg = lStrings.getString("http.method_put_not_supported");
            if (protocol.endsWith("1.1")) {
                resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
            } else {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            }
        }
        
     ...
    }
    

    此类中的service方法接收request和response两个参数,以及里边所有的doxxx()都接收这2个参数,也是一种策略模式的实现。

    五、优缺点

    1. 优点
    • 策略模式符合开闭原则,可以引入写的策略类而不用更改上下文

    • 可以在运行时切换不同的算法实现

    • 可以将算法的实现细节和使用的上下文隔离开,保证算法的安全性

    • 可以使用组合替换继承

    2. 缺点
    • 需要把所有的算法策略暴露给客户

    • 客户调用端需要知道不同算法之间的差异,方便去根据实际业务选择合适的策略

    • 会产生很多策略类,提升维护难度

    参考:
    https://refactoring.guru/design-patterns/strategy

    https://java-design-patterns.com/patterns/strategy/

    相关文章

      网友评论

        本文标题:java设计模式-策略模式

        本文链接:https://www.haomeiwen.com/subject/sdzcohtx.html