当前位置:首页 > 芯闻号 > 充电吧
[导读]策略模式的定义:定义一系列的算法类,将每一个算法封装起来,并让他们可以互相替换。策略模式让算法独立于使用它的客户而变化。下面是策略模式的结构图:其实,策略模式离我们很近,接下来看两个JDK中策略模式的

策略模式的定义:

定义一系列的算法类,将每一个算法封装起来,并让他们可以互相替换。策略模式让算法独立于使用它的客户而变化。

下面是策略模式的结构图:


其实,策略模式离我们很近,接下来看两个JDK中策略模式的例子。

Collections.sort()

在Collections类中,有个sort(List,Comparator)静态方法用于对给定的数组排序,至于两个对象怎么比较,java开发人员上哪知道去,所以就是使用这个方法的人自已定义的了。这不就是策略模式吗。下面从源代码中分析策略模式的实现。

在Collections类中:


public staticvoid sort(Listlist, Comparator c) {
  Object[] a = list.toArray();
  Arrays.sort(a, (Comparator)c);
  ListIterator i = list.listIterator();
  for (int j=0; j<a.length; j++) {
      i.next();
      i.set(a[j]);
  }
}


调用了Arrays类的sort()方法。ok,Arrays类走起。


public staticvoid sort(T[] a, Comparator c) {
  if (LegacyMergeSort.userRequested)
      legacyMergeSort(a, c);
  else
      TimSort.sort(a, c);
}


经过层层的调用,最终调用Arrays类的下面方法:


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; ilow && c.compare(dest[j-1], dest[j])>0; j--)
					swap(dest, j, j-1);
		return;
	}
	
	// Recursively sort halves of dest into src
	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 src) 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++];
	}
}


可以看到确实是调用了Comparator接口定义的方法。这里的Comparator就是策略类了,由用户自定义的算法,可以替换。下面看看使用这个方法的用户怎么使用这个神奇的方法:


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test{
	
	public static void main(String[] args){
		Liststudents = new ArrayList();
		students.add(new Student(12,"zhangsan"));
		students.add(new Student(13,"lisi"));
		students.add(new Student(11,"wangwu"));
		Collections.sort(students,new StudentComparator());
		for(Student s:students){
			System.out.println(s);
		}
	}
	
	private static class Student {
		private int age;
		private String name;
		public Student(int age,String name){
			this.age = age;
			this.name = name;
		}
		public String toString(){
			return age+","+name;
		}
		public int getAge() {
			return age;
		}
	}
	static class StudentComparator implements Comparator{

		@Override
		public int compare(Student o1, Student o2) {
			// TODO Auto-generated method stub
			return o1.getAge()-o2.getAge();
		}
		
	}


按学生的年龄给一个学生数组排序。哪天不想按年龄排序了,想按姓名排序,重新写一个Comparator的实现类并在客户端替换即可。从这里也可以看出这个设计模式是违反了开闭原则的。

File类的list()

list(FilenameFilter)方法用于列出目录下所有符合条件的文件。也是策略模式了,条件由用户自己定义。只要传入正则表达式即可。关于正则表达式,可以参看这里


public class FileTest {
	
	public void list(String path){
		File f = new File(path);
		String[] files = f.list(new FilenameFilterImpl(""));
		for(String s:files)
			System.out.println(s);
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new FileTest().list(".");
	}

}
class FilenameFilterImpl implements FilenameFilter{	
	private Pattern p;	
	public FilenameFilterImpl(String regex){
		p = Pattern.compile(regex);
	}

	@Override
	public boolean accept(File dir, String name) {
		// TODO Auto-generated method stub
		if(p.matcher(name).matches())
			return true;
		return false;
	}	
}


ok,策略模式还是很常见的设计模式,通过两个例子也可以看到其灵活性,就这样吧。

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭