package com.rain.Strategy; public class Cat implements Comparable<Cat>{ private int height; private int weight; public Cat(int height, int weight) { super(); this.height = height; this.weight = weight; } @Override public int compareTo(Cat o) { //根据身高排序 if(this.height>o.height) return 1; if(this.height<o.height) return -1; else return 0; } 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; } @Override public String toString() { return "Cat:"+this.height+"|"+this.weight+" "; } }
CatWeightComparator
package com.rain.Strategy; import java.util.Comparator; public class CatWeightComparator implements Comparator<Cat>{ @Override public int compare(Cat cat1, Cat cat2) { if(cat1.getWeight()>cat2.getWeight()) return 1; else if(cat1.getWeight()<cat2.getWeight()) return -1; else return 0; } }
Dog
package com.rain.Strategy; public class Dog implements Comparable<Dog>{ private int hairLong; public int getHairLong() { return hairLong; } public Dog(int hairLong) { super(); this.hairLong = hairLong; } public void setHairLong(int hairLong) { this.hairLong = hairLong; } @Override public String toString() { // TODO Auto-generated method stub return "Dog:"+this.hairLong+" "; } @Override public int compareTo(Dog o) { if(this.hairLong>o.hairLong) return 1; if(this.hairLong<o.hairLong) return -1; else return 0; } }
Strategy
package com.rain.Strategy; import java.util.Arrays; //一。规范:其他设备要想练到电脑上就要实现电脑的USB接口,不然Mp3是圆的接口,phone是正方形的接口, // 那电脑上得设多少接口才够啊!电脑这一端必须是长方形(规范)至于自己那一端(怎么实现)自己规定就好. //二。多态:连接电脑的可能是Mp3,Mp4,手机,相机。现在一个方法的功能ReadUSB(USB u) //Mp3,phone,camera都实现了USB这个接口,ReadUSB(mp3),ReadUSB(phone) 只要实现了USB接口的类都能读(多态) //三。可扩展:我们的程序要做到可扩展就要具备1.不需要改源代码 2.能在源代码基础上添加新功能。是添加新的类而不是原来的类里面改 //新加的类在原来写的类里面照样能用。比如上面的 传进来的USB参数u 是Mp3 我们调用u.getData那么只有声音,现在 //我想要图像 我们新写一个camera类实现USB接口然后传进去 这样u.getData得到的就是图像了 //我们要音乐有音乐要图像有图像是不是横牛逼 //这就叫接口编程:不需要关系具体的实现类是什么 只要调用接口就可以 USB u=new Mp3(); u.getData(); public class Strategy { //只要实现Comparable接口的类都能打印出来 //事先做好了规范以后新的类只要符合我的规范,现在的方法就可以调用以后实现的类 public static <T> void printObject(Comparable<T>[] list){ for(Comparable<T> c:list){ System.out.print(c); } System.out.println(); } public static void main(String[] args) { Cat cat1=new Cat(1, 50); Cat cat2=new Cat(6, 40); Cat cat3=new Cat(3, 66); Cat cat4=new Cat(4, 20); Cat cat5=new Cat(5, 10); Cat[] c={cat1,cat2,cat3,cat4,cat5}; Dog d1=new Dog(11); Dog d2=new Dog(22); Dog d3=new Dog(55); Dog d4=new Dog(33); Dog d5=new Dog(01); Dog[] d={d1,d2,d3,d4,d5}; Arrays.sort(d);//默认排序(根据Dog里实现的compareTo方法排序) Strategy.printObject(d); Arrays.sort(c);//默认排序(根据Cat里实现的compareTo方法排序) Strategy.printObject(c); Arrays.sort(c, new CatWeightComparator());//根据特定的排序器排序 Strategy.printObject(c); // 默认排序的逻辑是写在cat类里面的这样虽然方便, // 但是如果排序规则改变里(由比身高改成比体重,那么需要改cat的源代码 // 而第二种重新写一个排序器就可以在改变排序规则的时候不用源代码,只要在调用的地方修改下就好了 } }