您的位置:首页 > 其它

简单模拟Comparator-策略设计模式

2012-05-30 21:18 429 查看
//使一个类本身具备比较性
//优点:实现此接口的类可以自己重写自己规定比较的内容
//缺点:因为只有一个方法,一个类只能有一种方式进行比较
public interface MyComparable<E> {
public int compareTo(E e);
}
public interface MyComparator<T> {
int compare(T o1,T o2);
}
//排序类
public class DataSort {
public static void sort(Object[] objs){
for(int i=0;i<objs.length-1;i++){
for(int j=i+1;j<objs.length;j++){
MyComparable c1=(MyComparable)objs[i];
MyComparable c2=(MyComparable)objs[j];
if(c1.compareTo(c2)>0){
Object temp=objs[i];
objs[i]=objs[j];
objs[j]=temp;
}
}
}
}
}
//人
public class Person implements MyComparable<Person>{
//实现了MyComparator接口,对年龄进行排序的类
private MyComparator comage=new PersonAgeComparator();
//实现了MyComparator接口,对体重进行排序的类
private MyComparator comweight=new PersonWeightComparator();

private int weight;
private int age;
/*	使用这种匿名内部类的方式也可以,但是只能够实现一种方式的排序
*  因为Person类只有一个compareTo方法
* public int compareTo(Object e) {
return new MyComparator(){
public int compare(Object o1, Object o2) {
Person p1=(Person)o1;
Person p2=(Person)o2;
if(p1.age>p2.age)
return 1;
else if(p1.age<p2.age)
return -1;
return 0;
}}.compare(this, e);
}*/

public int compareTo(Person p){
//使用这种方式的话只要更改对象然后调用方法即可详细点的
//话可以开放外部的一个接口,让外部决定要哪种方式来进行
//排序,然后在类内部进行if判断即可,比如一个type属性来决定
//		return comage.compare(this, p);
return comweight.compare(this, p);
}
public Person(int age,int weight) {
super();
this.age = age;
this.weight=weight;
}
public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
//对Person类的年龄进行排序
public class PersonAgeComparator implements MyComparator<Person>{

public int compare(Person o1, Person o2) {
if(o1.getAge()>o2.getAge()){
return 1;
}else if(o1.getAge()<o2.getAge()){
return -1;
}
return 0;
}
}
//对Person类的体重来进行排序
public class PersonWeightComparator implements MyComparator<Person>{

public int compare(Person o1, Person o2) {
if(o1.getWeight()>o2.getWeight()){
return 1;
}else if(o1.getWeight()<o2.getWeight()){
return -1;
}
return 0;
}
}
public class Test {
public static void main(String[] args) {
Person[] ii={new Person(4,10),new Person(7,30),new Person(2,40),new Person(9,35)};
DataSort.sort(ii);
for(Person p:ii){
System.out.println(p.getAge()+":"+p.getWeight());
}
}
/**
* 对体重进行排序
* 运行结果:
* 4:10
* 7:30
* 9:35
* 9:35
* 2:40
*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: