策略模式,又叫算法簇模式,就是定义了不同的算法族,并且之间可以互相替换,此模式让算法的变化独立于使用算法的对象
例:对一群人进行排序,可以按身高排序也可以按体重排序还可以按姓名排序等等
第一版:实现功能满足需求
对这几种比较算法进行抽象化
public interface Comparator { int compare(Person p1, Person p2); }
按身高排序算法的实现
public class PersonHeightComparator implements Comparator { @Override public int compare(Person p1, Person p2) { if(p1.getHeight() > p2.getHeight()) return 1; else if(p1.getHeight() < p2.getHeight()) return -1; else return 0; } }
按体重排序算法的实现
public class PersonWeightComparator implements Comparator { @Override public int compare(Person p1, Person p2) { if(p1.getWeight() > p2.getWeight()) return 1; else if(p1.getWeight() < p2.getWeight()) return -1; else return 0; } }
Person类(支持设置不同的排序方法)
public class Person { private String name; private int height; private int weight; private Comparator comparator; public Person(String name, int height, int weight, Comparator comparator) { this.name = name; this.height = height; this.weight = weight; this.comparator = comparator; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int compareTo(Person p) { return comparator.compare(this, p); } @Override public String toString() { return name + ":" + height + "·" + weight; } }
测试
public class Test { public static void main(String[] args) { Comparator comparator = new PersonHeightComparator(); // = new PersonWeightComparator(); Person[] persons = new Person[] { new Person("a", 175, 68, comparator), new Person("b", 178, 67, comparator), new Person("c", 173, 66, comparator) }; sort(persons); // 利用排序算法对persons进行排序 System.out.println(Arrays.toString(persons)); } public static void sort(Person[] persons) { for(int i=0; i<persons.length; i++) { for(int j=0; j<persons.length-i-1; j++) { Person p1 = persons[j]; Person p2 = persons[j+1]; if(p1.compareTo(p2) > 0) { persons[j] = p2; persons[j+1] = p1; } } } } }
OK,需求已实现了。按身高、体重的排序算法能否也能应用的其它可以排序的事物上呢,答案是肯定。
第二版:完成第一版遗留的问题
1. 对可以排序的对象进行抽象
2. 泛型化
public interface Comparable<T> { public int compareTo(T o); } public interface Comparator<T> { int compare(T o1, T o2); } public class Person implements Comparable<Person> { public class PersonHeightComparator implements Comparator<Person> { // 与上面相同 } public class PersonWeightComparator implements Comparator<Person> { // 与上面相同 }
OK,这就是JDK中已经实现的Comparator策略。