详解Java编程中的策略模式

网友投稿 198 2023-07-30


详解Java编程中的策略模式

策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。

策略模式的结构

策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理。策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。用一句话来说,就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换”。下面就以一个示意性的实现讲解策略模式实例的结构。

这个模式涉及到三个角色:

环境(Context)角色:持有一个Strategy的引用。

抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。

具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。

源代码

  环境角色类

public class Context {

//持有一个具体策略的对象

private Strategy strategy;

/**

* 构造函数,传入一个具体策略对象

* @param strategy 具体策略对象

*/

public Context(Strategy strategy){

this.strategy = strategy;

}

/**

* 策略方法

*/

public void contextInterface(){

strategy.strategyInterface();

}

}

抽象策略类

public interface Strategy {

/**

* 策略方法

*/

public void strategyInterface();

}

具体策略类

public class ConcreteStrategyA implements Strategy {

@Override

public void strategyInterface() {

//相关的业务

}

}

public class ConcreteStrategyB implements Strategy {

@Override

public void strategyInterface() {

//相关的业务

}

}

public class ConcreteStrategyC implements Strategy {

@Override

public void strategyInterface() {

//相关的业务

}

}

以策略模式分析java源码

声明:这里参考了Java源码分析-策略模式在Java集合框架实现代码中的体现

在java的集合框架中,构造Map或者Set时传入Comparator比较器,或者创建比较器传入Collections类的静态方法中作为方法的参数为Collection排序时,都使用了策略模式

简单的调用代码:

import java.util.*;

public class TestComparator {

public static void main(String args[]) {

LinkedList list = new LinkedList();

list.add("wangzhengyi");

list.add("bululu");

// 创建一个逆序比较器

Comparator r = Collections.reverseOrder();

// 通过逆序比较器进行排序

Collections.sort(list, r);

System.out.println(list);

}

}

使用Collections.reverseOrder()方法实现一个比较器后,再调用Collections.sort(list, r)把比较器传入该方法中进行排序,下面看一下sort(list, r)中的代码:

public static void sort(List list, Comparator super T> c) {

Object[] a = list.toArray();

Arrays.sort(a, (Comparator)c);

ListIterator i = list.listIterator();

for (int j=0; j

i.next();

i.set(a[j]);

}

}

Array.sort(a, (Comparator)c);这句继续把比较器传入处理,下面是Array.sort(a, (Comparator)c)的具体操作:

public static void sort(T[] a, Comparator super T> c) {

if (LegacyMergeSort.userRequested)

legacyMergeSort(a, c);

else

TimSort.sort(a, c);

}

static void sort(T[] a, Comparator super T> c) {

sort(a, 0, a.length, c);

}

/** To be removed in a future release. */

private static void legacyMergeSort(T[] a, Comparator super T> c) {

T[] aux = a.clone();

if (c==null)

mergeSort(aux, a, 0, a.length, 0);

else

mergeSort(aux, a, 0, a.length, 0, c);

}

继续跟下去好了:

private static void mergeSort(Object[] src,

Object[] dest,

int low, int high, int off,

Comparator c) {

int length = high - low;

// Insertion sort on smallest arrays

if (length < INSERTIONSORT_THRESHOLD) {

for (int i=low; i

for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)

swap(dest, j, j-1);

return;

}

// Recursively sort halves of dest into src

http:// int destLow = low;

int destHigh = high;

low += off;

high += off;

int mid = (low + high) >>> 1;

mergeSort(dest, src, low, mid, -off, c);

mergeSort(dest, src, mid, high, -off, c);

// If list is already sorted, just copy from src to dest. This is an

// optimization that results in faster sorts for nearly ordered lists.

if (c.compare(src[mid-1], src[mid]) <= 0) {

System.arraycopy(src, low, dest, destLow, length);

return;

}

// Merge sorted halves (now in shttp://rc) into dest

for(int i = destLow, p = low, q = mid; i < destHigh; i++) {

if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)

dest[i] = src[p++];

else

dest[i] = src[q++];

}

}

把使用到比较器的代码挑选出来:

// If list is already sorted, just copy from src to dest. This is an

// optimization that results in faster sorts for nearly ordered lists.

if (c.compare(src[mid-1], src[mid]) <= 0) {

System.arraycopy(src, low, dest, destLow, length);

return;

}

这里的compare方法在Comparator接口中也有定义:

public interface Comparator {

int compare(T o1, T o2);

}

由于这里是泛型实现了Comparator,所以实际执行时,会根据比较器的具体实现类调用到实现代码,也就是上面创建的逆序比较器的compare方法,其实现方法如下:

public int compare(Comparable c1, Comparable c2) {

return c2.compareTo(c1);

}

i.next();

i.set(a[j]);

}

}

Array.sort(a, (Comparator)c);这句继续把比较器传入处理,下面是Array.sort(a, (Comparator)c)的具体操作:

public static void sort(T[] a, Comparator super T> c) {

if (LegacyMergeSort.userRequested)

legacyMergeSort(a, c);

else

TimSort.sort(a, c);

}

static void sort(T[] a, Comparator super T> c) {

sort(a, 0, a.length, c);

}

/** To be removed in a future release. */

private static void legacyMergeSort(T[] a, Comparator super T> c) {

T[] aux = a.clone();

if (c==null)

mergeSort(aux, a, 0, a.length, 0);

else

mergeSort(aux, a, 0, a.length, 0, c);

}

继续跟下去好了:

private static void mergeSort(Object[] src,

Object[] dest,

int low, int high, int off,

Comparator c) {

int length = high - low;

// Insertion sort on smallest arrays

if (length < INSERTIONSORT_THRESHOLD) {

for (int i=low; i

for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)

swap(dest, j, j-1);

return;

}

// Recursively sort halves of dest into src

http:// int destLow = low;

int destHigh = high;

low += off;

high += off;

int mid = (low + high) >>> 1;

mergeSort(dest, src, low, mid, -off, c);

mergeSort(dest, src, mid, high, -off, c);

// If list is already sorted, just copy from src to dest. This is an

// optimization that results in faster sorts for nearly ordered lists.

if (c.compare(src[mid-1], src[mid]) <= 0) {

System.arraycopy(src, low, dest, destLow, length);

return;

}

// Merge sorted halves (now in shttp://rc) into dest

for(int i = destLow, p = low, q = mid; i < destHigh; i++) {

if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)

dest[i] = src[p++];

else

dest[i] = src[q++];

}

}

把使用到比较器的代码挑选出来:

// If list is already sorted, just copy from src to dest. This is an

// optimization that results in faster sorts for nearly ordered lists.

if (c.compare(src[mid-1], src[mid]) <= 0) {

System.arraycopy(src, low, dest, destLow, length);

return;

}

这里的compare方法在Comparator接口中也有定义:

public interface Comparator {

int compare(T o1, T o2);

}

由于这里是泛型实现了Comparator,所以实际执行时,会根据比较器的具体实现类调用到实现代码,也就是上面创建的逆序比较器的compare方法,其实现方法如下:

public int compare(Comparable c1, Comparable c2) {

return c2.compareTo(c1);

}

for (int j=i; j>low && c.compare(dest[j-1], dest[j])>0; j--)

swap(dest, j, j-1);

return;

}

// Recursively sort halves of dest into src

http:// int destLow = low;

int destHigh = high;

low += off;

high += off;

int mid = (low + high) >>> 1;

mergeSort(dest, src, low, mid, -off, c);

mergeSort(dest, src, mid, high, -off, c);

// If list is already sorted, just copy from src to dest. This is an

// optimization that results in faster sorts for nearly ordered lists.

if (c.compare(src[mid-1], src[mid]) <= 0) {

System.arraycopy(src, low, dest, destLow, length);

return;

}

// Merge sorted halves (now in shttp://rc) into dest

for(int i = destLow, p = low, q = mid; i < destHigh; i++) {

if (q >= high || p < mid && c.compare(src[p], src[q]) <= 0)

dest[i] = src[p++];

else

dest[i] = src[q++];

}

}

把使用到比较器的代码挑选出来:

// If list is already sorted, just copy from src to dest. This is an

// optimization that results in faster sorts for nearly ordered lists.

if (c.compare(src[mid-1], src[mid]) <= 0) {

System.arraycopy(src, low, dest, destLow, length);

return;

}

这里的compare方法在Comparator接口中也有定义:

public interface Comparator {

int compare(T o1, T o2);

}

由于这里是泛型实现了Comparator,所以实际执行时,会根据比较器的具体实现类调用到实现代码,也就是上面创建的逆序比较器的compare方法,其实现方法如下:

public int compare(Comparable c1, Comparable c2) {

return c2.compareTo(c1);

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:图解Spring框架的设计理念与设计模式
下一篇:将页面table内容与样式另存成excel文件的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~