简单模拟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 */ }
相关文章推荐
- 简单模拟Comparator-策略设计模式-马士兵设计模式教程
- Java-马士兵设计模式学习笔记-策略模式-模拟 Comparator接口
- HEAD_FIRST设计模式学习 ----策略模式 c++简单实现代码
- 设计模式之六:命令模式(简单实现(餐厅点餐模拟流程))
- 设计模式 学习笔记(1)简单工厂模式、策略模式
- 设计模式之二:观察者模式(简单实现(气象站模拟流程))
- 设计模式解读 之策略模式(参照策略模式与简单工厂模式的对比)
- 简单模拟ArrayList-迭代器设计模式
- 设计模式——简单工厂+策略模式
- 【设计模式】简单工程模式和策略模式的区别
- 设计模式——策略模式:会员价格体系的简单实现
- 设计模式随笔-策略模式与简单工厂的区别
- 适配器设计模式,简单的Java代码模拟
- 关于一个简单的策略设计模式的例子
- 设计模式-简单工厂设计模式与策略模式之java实现二
- 设计模式笔记——策略模式VS简单工厂模式
- JDK设计模式之——策略模式(Comparable和Comparator接口)
- Java设计模式——Comparable接口&&Comparator(CC系)策略模式的应用
- 简单模拟Comparable-策略模式
- 设计模式学习笔记一 简单工厂策略模式实现销售策略的变更(一)