策略模式:就是说,当我需要对对象比较大小的时候,我定义一个策略的比较器,然后由具体的比较策略来决定谁大谁小
Comparable接口的作用
DataSort中sort(Comparable c)方法假设所有参与比较的对象都是实现了Comparable接口类的对象,这样就把所有需要进行比较的类统一了起来,排序时就调用每个类自定义的compareTo(Comparable c)方法。所以可以这样说,Comparable是为统一所有需要进行比较的类而设置的
Comparator接口的作用
Cat和Dog中compareTo(Comparalbe c)方法假设所有的比较器都是实现了Comparator接口类的对象,这样就把所有具体的比较器统一了起来,比较时就调用每个比较器自定义的compare(Comparable c1,Comparable c2)方法。所以,Comparator是为所有要比较的类所持有的比较器而设置的
这样不仅在需要进行比较的类上实现了扩展,在每个类具体的比较策略上,也实现了扩展,可扩展性Extensibility,是面向对象的精华。
注:当然jdk早就提供了上述两种接口,只要实现了Comparable接口,java.util.Arrays.sort(xxx);(xxx为数组)就可以帮助自动排序(其中sort()方法注释有一句话:All elements in the array must implement the Comparable interface.),,,自己模拟这个过程为了帮助理解这种模式
代码部分:
Comparable接口
package com.chouwu;
public interface Comparable {
int compareTo(Comparable c);
}
Comparator接口
package com.chouwu;
public interface Comparator {
int compare(Comparable c1,Comparable c2);
}
需要进行比较的类一Cat
package com.chouwu;
public class Cat implements Comparable {
private int height;
private int weight;
//先默认定义一个,可通过set方法来更改比较器
static Comparator comparator = new CatHeightComparator();
public Cat(int height, int weight) {
this.height = height;
this.weight = weight;
}
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 Comparator getComparator() {
return comparator;
}
public void setComparator(Comparator comparator) {
this.comparator = comparator;
}
@Override
public String toString() {
return "Cat [height=" + height + ", weight=" + weight + "]";
}
@Override
public int compareTo(Comparable c) {
return comparator.compare(this, c);
}
}
Cat类比较器:身高比较器
package com.chouwu;
public class CatHeightComparator implements Comparator {
@Override
public int compare(Comparable c1, Comparable c2) {
//未使用泛型,所以并未考虑不同种类之间进行比较的错误情况
//谁高谁大
if (((Cat) c1).getHeight() > ((Cat) c2).getHeight())
return 1;
else if (((Cat) c1).getHeight() < ((Cat) c2).getHeight())
return -1;
else
return 0;
}
}
Cat类比较器:体重比较器
package com.chouwu;
public class CatWeightComparator implements Comparator {
@Override
public int compare(Comparable c1, Comparable c2) {
//并未考虑不同种类之间会进行比较的错误情况
//便于测试,谁重谁小
if (((Cat) c1).getWeight() > ((Cat) c2).getWeight())
return -1;
else if (((Cat) c1).getWeight() < ((Cat) c2).getWeight())
return 1;
else
return 0;
}
}
测试用主程序Test
package com.chouwu;
public class Test {
public static void main(String[] args) {
Comparable[] c = new Cat[]{new Cat(4,4),new Cat(6,6),new Cat(5,5),new Cat(3,3)};
//Comparable[] d = new Dog[]{new Dog(4),new Dog(6),new Dog(5),new Dog(3)}; //第二个需要进行比较的类,本文没有呈现该类
DataSort.sort(c);
DataSort.print(c);
//DataSort.sort(d);
//DataSort.print(d);
}
}