使用策略模式自定义对象排序和比较属性值排序的例子
/**
*
* 实体类的接口
*
*/
public interface DongWu {
public int getAge();
public void setAge(int age) ;
public int getHigh();
public void setHigh(int high) ;
}
/**
*
* 排序接口
*
*/
public interface MyComparator {
int comparatorTo(Object object);
}
/**
*
* 具体的排序接口,和具体的实体类对象无关
*
*/
public interface TypeComparator {
int comparatorTo(Object object1,Object object2);
}
/**
*
* 按照年纪倒叙排序
*
*/
public class AgeDescTypeComparator implements TypeComparator {
@Override
public int comparatorTo(Object object1, Object object2) {
DongWu c1 = (DongWu) object1;
DongWu dw = (DongWu) object2;
if (c1.getAge() > dw.getAge()) {
return -1;
} else if (c1.getAge() < dw.getAge()) {
return 1;
}
return 0;
}
}
/**
*
* 按照年纪正叙排序
*
*/
public class AgeTypeComparator implements TypeComparator {
@Override
public int comparatorTo(Object object1, Object object2) {
DongWu c1 = (DongWu) object1;
DongWu dw = (DongWu) object2;
if (c1.getAge() > dw.getAge()) {
return 1;
} else if (c1.getAge() < dw.getAge()) {
return -1;
}
return 0;
}
}
public class Cat implements MyComparator,DongWu{
private int age;
private int high;
private TypeComparator typeComparator =new AgeDescTypeComparator();
public Cat(){}
public Cat(int age){
this.age=age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
@Override
public int comparatorTo(Object object) {
DongWu cat = (DongWu) object;
return typeComparator.comparatorTo(this, cat);
}
}
public class Dog implements MyComparator,DongWu{
private int age;
private int high;
private TypeComparator typeComparator =new AgeDescTypeComparator();
public Dog(){}
public Dog(int age){
this.age=age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHigh() {
return high;
}
public void setHigh(int high) {
this.high = high;
}
@Override
public int comparatorTo(Object object) {
DongWu d = (DongWu) object;
return typeComparator.comparatorTo(this, d);
}
}
public class DataSorter {
public static void sort(MyComparator[] arr){
for (int i = arr.length; i >0 ; i--) {
for(int j=0;j<i-1;j++){
MyComparator m1=arr[j];
MyComparator m2= arr[j+1];
if(m1.comparatorTo(m2)==1){
swap(arr,j,j+1);
}
}
}
}
private static void swap(Object[] arr, int j, int i) {
Object temp =arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}