设计模式 ~ 行为型模式 ~ 策略模式 ~ Strategy Pattern。
what。
我们去旅游选择出行模式有很多种,可以骑自行车、可以坐汽车、可以坐火车、可以坐飞机。
作为一个程序猿,开发需要选择一款开发工具,当然可以进行代码开发的工具有很多,可以选择 IntelliJIDEA 进行开发,也可以使用 Eclipse 进行开发,也可以使用其他的一些开发工具。
该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。
结构。
策略模式的主要角色如下。
-
抽象策略(Strategy)类。
这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有
的具体策略类所需的接口。 -
具体策略(Concrete Strategy)类。
实现了抽象策略定义的接口,提供具体的算法实现或行为。 -
环境(Context)类。
持有一个策略类的引用,最终给客户端调用。
【eg.】促销活动。
一家百货公司在定年度的促销活动。针对不同的节日(春节、中秋节、圣诞节)推出不同的促销活动,由促销员将促销活动展示给客户。
package com.geek.strategy;
/**
* 百货公司所有促销活动的共同接口 ~ 抽象策略。
*
* @author geek
*/
public interface IStrategy {
void show();
}
具体策略角色(Concrete Strategy):每个节日具体的促销活动。
package com.geek.strategy;
/**
* 为春节准备的促销活动。
*
* @author geek
*/
public class StrategyA implements IStrategy {
@Override
public void show() {
System.out.println("为春节准备的促销活动 ~ 买一送一。");
}
}
package com.geek.strategy;
/**
* 具体策略类 ~ 封装算法。
* 为春节准备的促销活动。
*
* @author geek
*/
public class StrategyA implements IStrategy {
@Override
public void show() {
System.out.println("为春节准备的促销活动 ~ 买一送一。");
}
}
package com.geek.strategy;
/**
* 具体策略类 ~ 封装算法。
* 为圣诞准备的促销活动。
*
* @author geek
*/
public class StrategyC implements IStrategy {
@Override
public void show() {
System.out.println("为圣诞准备的促销活动 ~ 满 1000 元加一元换购任意 200 元以下商品。");
}
}
环境角色(Context):用于连接上下文,即把促销活动推销给客户,这里可以理解为销售员。
package com.geek.strategy;
/**
* 环境角色(Context)。
* 用于连接上下文。
* 即把促销活动推销给客户,这里可以理解为销售员。
*
* @author geek
*/
public class SalesMan {
/**
* 聚合策略类对象。
* 持有抽象策略角色的引用。
*/
private IStrategy strategy;
public SalesMan(IStrategy strategy) {
this.strategy = strategy;
}
/**
* 促销员向客户展示促销活动。
*/
public void salesManShow() {
strategy.show();
}
}
package com.geek.strategy;
/**
* @author geek
*/
public class Client {
public static void main(String[] args) {
// 春节来了,使用春节促销活动。
IStrategy strategyA = new StrategyA();
SalesMan salesMan = new SalesMan(strategyA);
// 销售员展示促销活动。
salesMan.salesManShow();
// 为春节准备的促销活动 ~ 买一送一。
// 中秋节来了,使用中秋节促销活动。
IStrategy strategyB = new StrategyB();
salesMan.setStrategy(strategyB);
// 销售员展示促销活动。
salesMan.salesManShow();
// 为中秋准备的促销活动 ~ 满 200 减 50。
// 圣诞来了,使用圣诞促销活动。
IStrategy strategyC = new StrategyC();
salesMan.setStrategy(strategyC);
// 销售员展示促销活动。
salesMan.salesManShow();
// 为圣诞准备的促销活动 ~ 满 1000 元加一元换购任意 200 元以下商品。
}
}
优点。
-
策略类之间可以自由切换。
由于策略类都实现同一个接口,所以使它们之间可以自由切换。 -
易于扩展。
增加一个新的策略只需要添加一个具体的策略类即可,基本不需要改变原有的代码,符合“开闭原则“。
避免使用多重条件选择语句(if else),充分体现面向对象设计思想。
缺点。
-
客户端必须知道所有的策略类,并自行决定使用哪一个策略类。
-
策略模式将造成产生很多策略类,可以通过使用享元模式在一定程度上减少对象的数量。
使用场景。
-
一个系统需要动态地在几种算法中选择一种时,可将每个算法封装到策略类中。
-
一个类定义了多种行为,并且这些行为在这个类的操作中以多个条件语句的形式出现,可将每个条件分支移入它们各自的策略类中以代替这些条件语句。
-
系统中各算法彼此完全独立,且要求对客户隐藏具体算法的实现细节时。
-
系统要求使用算法的客户不应该知道其操作的数据时,可使用策略模式来隐藏与算法相关的数据结构。
-
多个类只区别在表现行为不同,可以使用策略模式,在运行时动态选择具体要执行的行为。
JDK 源码解析。
Comparator 中的策略模式。在 Arrays 类中有一个 sort(); 方法。
public class Arrays {
/**
* Sorts the specified array of objects according to the order induced by
* the specified comparator. All elements in the array must be
* <i>mutually comparable</i> by the specified comparator (that is,
* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
* for any elements {@code e1} and {@code e2} in the array).
*
* <p>This sort is guaranteed to be <i>stable</i>: equal elements will
* not be reordered as a result of the sort.
*
* <p>Implementation note: This implementation is a stable, adaptive,
* iterative mergesort that requires far fewer than n lg(n) comparisons
* when the input array is partially sorted, while offering the
* performance of a traditional mergesort when the input array is
* randomly ordered. If the input array is nearly sorted, the
* implementation requires approximately n comparisons. Temporary
* storage requirements vary from a small constant for nearly sorted
* input arrays to n/2 object references for randomly ordered input
* arrays.
*
* <p>The implementation takes equal advantage of ascending and
* descending order in its input array, and can take advantage of
* ascending and descending order in different parts of the the same
* input array. It is well-suited to merging two or more sorted arrays:
* simply concatenate the arrays and sort the resulting array.
*
* <p>The implementation was adapted from Tim Peters's list sort for Python
* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">
* TimSort</a>). It uses techniques from Peter McIlroy's "Optimistic
* Sorting and Information Theoretic Complexity", in Proceedings of the
* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,
* January 1993.
*
* @param <T> the class of the objects to be sorted
* @param a the array to be sorted
* @param c the comparator to determine the order of the array. A
* {@code null} value indicates that the elements'
* {@linkplain Comparable natural ordering} should be used.
* @throws ClassCastException if the array contains elements that are
* not <i>mutually comparable</i> using the specified comparator
* @throws IllegalArgumentException (optional) if the comparator is
* found to violate the {@link Comparator} contract
*/
public static <T> void sort(T[] a, Comparator<? super T> c) {
if (c == null) {
sort(a);
} else {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a, c);
else
TimSort.sort(a, 0, a.length, c, null, 0, 0);
}
}
}
Arrays 就是一个环境角色类,这个 sort(); 方法可以传一个新策略让 Arrays 根据这个策略来进行排序。
eg. 测试类。
package com.geek.strategy.demo;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author geek
*/
public class Demo {
public static void main(String[] args) {
Integer[] data = {12, 2, 3, 4, 2, 5, 1};
// 实现降序排序。
Arrays.sort(data, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
System.out.println(Arrays.toString(data));
// [12, 5, 4, 3, 2, 2, 1]
}
}
这里我们在调用 Arrays 的 sort(); 方法时,第二个参数传递的是 Comparator 接口的子实现类对象。所以 Comparator 充当的是抽象策略角色,而具体的子实现类充当的是具体策略角色。环境角色类
(Arrays)应该持有抽象策略的引用来调用。那么,Arrays 类的 sort(); 方法到底有没有使用 Comparator 子实现类中的 compare(); 方法呢?让我们继续查看 TimSort 类的 sort(); 方法。
class TimSort<T> {
/**
* Sorts the given range, using the given workspace array slice
* for temp storage when possible. This method is designed to be
* invoked from public methods (in class Arrays) after performing
* any necessary array bounds checks and expanding parameters into
* the required forms.
*
* @param a the array to be sorted
* @param lo the index of the first element, inclusive, to be sorted
* @param hi the index of the last element, exclusive, to be sorted
* @param c the comparator to use
* @param work a workspace array (slice)
* @param workBase origin of usable space in work array
* @param workLen usable size of work array
* @since 1.8
*/
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
T[] work, int workBase, int workLen) {
assert c != null && a != null && lo >= 0 && lo <= hi && hi <= a.length;
int nRemaining = hi - lo;
if (nRemaining < 2)
return; // Arrays of size 0 and 1 are always sorted
// If array is small, do a "mini-TimSort" with no merges
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
binarySort(a, lo, hi, lo + initRunLen, c);
return;
}
。。。
/**
* Returns the length of the run beginning at the specified position in
* the specified array and reverses the run if it is descending (ensuring
* that the run will always be ascending when the method returns).
*
* A run is the longest ascending sequence with:
*
* a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
*
* or the longest descending sequence with:
*
* a[lo] > a[lo + 1] > a[lo + 2] > ...
*
* For its intended use in a stable mergesort, the strictness of the
* definition of "descending" is needed so that the call can safely
* reverse a descending sequence without violating stability.
*
* @param a the array in which a run is to be counted and possibly reversed
* @param lo index of the first element in the run
* @param hi index after the last element that may be contained in the run.
It is required that {@code lo < hi}.
* @param c the comparator to used for the sort
* @return the length of the run beginning at the specified position in
* the specified array
*/
private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi,
Comparator<? super T> c) {
assert lo < hi;
int runHi = lo + 1;
if (runHi == hi)
return 1;
// Find end of run, and reverse range if descending
if (c.compare(a[runHi++], a[lo]) < 0) { // Descending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0)
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0)
runHi++;
}
return runHi - lo;
}
}
上面的代码中最终会跑到 countRunAndMakeAscending(); 这个方法中。我们可以看见,只用了 compare(); 方法,所以在调用 Arrays.sort(); 方法只传具体 compare(); 重写方法的类对象就行,这也是 Comparator 接口中必须要子类实现的一个方法。