단순 시 뮬 레이 션 Comparator - 전략 설계 모드

2823 단어
//           
//  :                      
//  :        ,              
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
 */
}

좋은 웹페이지 즐겨찾기