【设计模式】策略模式Strategy_02

来源:互联网 发布:牛知天骄潮汕鲜牛肉 编辑:程序博客网 时间:2024/05/20 03:38
接着上一篇总结继续探讨。
之前我们的DataSorter的Sort方法虽然可以对任何实现了Comparable接口的对象进行排序,不过,麻烦事在于,这些对象实现的comparaTo方法只有一种实现,只能写一种,不能写太多,而且将来我想任意的扩展怎么计算两个对象谁大谁小的规范,这个时候这个类该如何设计呢?

现在我们对其进行实现。大家想想看,我们想对两个对象比较大小的方式进行拓展,这个方式就不能定义为具体的,要定义为抽象的,所以我们定义这样一个接口:
比较器Comparator.java:
package cn.edu.hpu.Strategy;//interface类里面的方法默认都是publicpublic interface Comparator {/*实现这个接口的对象使用这个方法进行比较时,*返回1是比那个对象大,返回0是相等,返回-1是比那个对象小*/int compare(Object o1,Object o2);}

我们之前对狗进行的是利用高度进行排序,现在我们用其重量来比较大小。
我们重新创建一个类,叫做"狗的根据重量的比较器",它去实现Comparator接口
package cn.edu.hpu.Strategy;public class DogWeightComparator implements Comparator{@Overridepublic int compare(Object o1, Object o2) {Dog d1=(Dog)o1;Dog d2=(Dog)o2;if(d1.getWeight()>d2.getWeight()) return 1;else if(d1.getWeight()<d2.getWeight()) return -1;return 0;}}

对于狗来说,我们之前实现Comparable接口了,此时比较逻辑不要在comparaTo()方法中写死,我们在comparaTo()中new出一个DogWeightComparator比较器,来比较当前的对象和传进来的对象的大小。
package cn.edu.hpu.Strategy;public class Dog implements Comparable{//狗的身高private int height;//狗的体重private int weight;public Dog(int height, int weight) {super();this.height = height;this.weight = weight;}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;}@Overridepublic int compareTo(Object o) {return new DogWeightComparator().compare(this, o);}@Overridepublic String toString() {return this.getHeight()+"|"+this.getWeight();}}

这个时候你就会发现好处:假如我对重量比较不满意了,我可以换成new别的来实现别的比较方法。
我们最好设置一个成员变量,是比较器Comparator类型的,设好它的get和set方法,具体向里面放什么样的比较器,我们在comparaTo()方法中就引用什么样的比较器来比较大小。
package cn.edu.hpu.Strategy;public class Dog implements Comparable{//狗的身高private int height;//狗的体重private int weight;//比较器(默认指定DogWeightComparator)private Comparator comparator=new DogWeightComparator();public Dog(int height, int weight) {super();this.height = height;this.weight = weight;}public Comparator getComparator() {return comparator;}public void setComparator(Comparator comparator) {this.comparator = comparator;}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;}@Overridepublic int compareTo(Object o) {return comparator.compare(this, o);}@Overridepublic String toString() {return this.getHeight()+"|"+this.getWeight();}}
测试:
package cn.edu.hpu.Strategy;public class Test {public static void main(String[] args) {; Dog[] dogs={new Dog(3,8),new Dog(5,4),new Dog(1,2)};DataSorter.sort(dogs); DataSorter.p(dogs);}}

结果:
1|2 5|4 3|8 
我们发现使用狗的重量来排序了。

当我们使用新创建的Comparator接口的时候,你会发现世界又美好了一些,因为我写完一个Dog类之后我还可以跟着设置他们两个对象之间的比较方式,这样我们类的扩展能力就更强了。

大家仔细想想Comparable、Comparator接口与DataSorter和比较类Dog、Cat之间的关系,就会总结出Comparator接口出现的好处。

下一篇总结收尾。

转载请注明出处:http://blog.csdn.net/acmman/article/details/46634565

0 0
原创粉丝点击