策略模式

策略模式

策略模式的用意是针对一组算法,将每一个算法封装到具有共同接口的独立类中,从而使它们可以相互替换。

策略模式是对算法的包装,是把算法使用和算法本身分开。策略模式通常是把一系列算法包装到一系列的策略里面,作为一个抽象策略类的子类。

涉及的角色

1.环境角色

持有一个策略的引用

2.抽象策略角色

一个抽象策略角色,通常由一个接口或者抽象类实现,此角色给出所有具有策略类所需的接口。

3.具体策略角色

包装相关算法或者行为。

实例

抽象策略

1 public interface AbstractStrategy {
2 
3     public void use();
4 }

两种具体的策略

1 public class StrategyA implements AbstractStrategy{
2 
3     public void use() {
4         System.out.println("use strategyA");
5     }
6     
7 }
1 public class StrategyB implements AbstractStrategy{
2 
3         public void use() {
4             System.out.println("use strategyB");
5         }
6 }

策略的引用

 1 public class Context {
 2 
 3     private AbstractStrategy strategy;
 4     
 5     public Context(AbstractStrategy strategy){
 6         this.strategy = strategy;
 7     }
 8     
 9     public void strategyMethod(){
10         strategy.use();
11     }
12     
13 }

具体调用

1 public static void main(String[] args) {
2         StrategyA strategyA = new StrategyA();
3         StrategyB strategyB = new StrategyB();
4         Context contextA = new Context(strategyA);
5         contextA.strategyMethod();
6         Context contextB = new Context(strategyB);
7         contextB.strategyMethod();
8     }

策略模式的使用场景

比如购物系统用户付款,会产生多种场景,根据用户不同的情况算出不同用户要付款的金额,那么最直观的做法就是多个if else。这种设计明显是违法了开闭原则,这里是指,对于修改关闭,比如算法多了几种,那么必须再次修改这个付款类。这时候可以使用策略模式,

付款类里面持有一个付款接口的引用,每次根据不同场景传入一个具体的策略就ok了。

策略模式在java中的应用

comparator接口。比如collections里面有一个sort方法,因为集合里面的元素可能是复合对象,复合对象并不像基本数据类型,可以根据大小排序,复合对象怎么排序?基于这个考虑,java要求如果定义的复合对象要有排序功能就自行实现Comparable接口或者comparator接口。

1 public static <T> void sort(List<T> list, Comparator<? super T> c) {
2     Object[] a = list.toArray();
3     Arrays.sort(a, (Comparator)c);
4     ListIterator i = list.listIterator();
5     for (int j=0; j<a.length; j++) {
6         i.next();
7         i.set(a[j]);
8     }
9     }

跟第3行

1 public static <T> void sort(T[] a, Comparator<? super T> c) {
2     T[] aux = (T[])a.clone();
3         if (c==null)
4             mergeSort(aux, a, 0, a.length, 0);
5         else
6             mergeSort(aux, a, 0, a.length, 0, c);
7     }

跟第6行

 1 private static void mergeSort(Object[] src,
 2                   Object[] dest,
 3                   int low, int high, int off,
 4                   Comparator c) {
 5     int length = high - low;
 6 
 7     // Insertion sort on smallest arrays
 8     if (length < INSERTIONSORT_THRESHOLD) {
 9         for (int i=low; i<high; i++)
10         for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)
11             swap(dest, j, j-1);
12         return;
13     }
14 
15         // Recursively sort halves of dest into src
16         int destLow  = low;
17         int destHigh = high;
18         low  += off;
19         high += off;
20         int mid = (low + high) >>> 1;
21         mergeSort(dest, src, low, mid, -off, c);
22         mergeSort(dest, src, mid, high, -off, c);
23 
24         // If list is already sorted, just copy from src to dest.  This is an
25         // optimization that results in faster sorts for nearly ordered lists.
26         if (c.compare(src[mid-1], src[mid]) <= 0) {
27            System.arraycopy(src, low, dest, destLow, length);
28            return;
29         }
30 
31         // Merge sorted halves (now in src) into dest
32         for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
33             if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)
34                 dest[i] = src[p++];
35             else
36                 dest[i] = src[q++];
37         }
38     }

这就是策略模式,我们可以给Collections的sort方法传入不同的Comparator的实现类作为不同的比较策略。不同的比较策略,对同一个集合,可能会产生不同的排序结果。mergeSort是归并排序。

策略模式的优缺点

优点:

1.避免多重if else,不容易维护。

2.提供了管理相关算法簇的办法,恰当使用继承可以把公共代码移到父类,从而避免了代码重复。

缺点:

1.客户端必须知道使用寿命策略,必须理解各种算法的区别。

原文地址:https://www.cnblogs.com/tp123/p/6489758.html