(4)设计模式:Strategy

来源:互联网 发布:知乎日报mac 百度网盘 编辑:程序博客网 时间:2024/06/09 19:45

设计模式:Strategy


就是说在进行比较大小的时候,定义一个策略的比较器,然后具体的策略比较谁大谁小。


package com.bjsxt.dp.strategy;public class Cat implements java.lang.Comparable<Cat> {private int height;//private Comparator comparator = new CatHeightComparator();private java.util.Comparator<Cat> comparator = new CatHeightComparator();public java.util.Comparator getComparator() {return comparator;}public void setComparator(java.util.Comparator comparator) {this.comparator = comparator;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}public Cat(int height, int weight) {super();this.height = height;this.weight = weight;}public int getWeight() {return weight;}public void setWeight(int weight) {this.weight = weight;}private int weight;@Overridepublic String toString() {return height + "|" + weight;}@Overridepublic int compareTo(Cat o) {return comparator.compare(this, o);}}


<span style="font-family: Arial, Helvetica, sans-serif;">package com.bjsxt.dp.strategy;</span>
public class CatHeightComparator implements java.util.Comparator<Cat> {@Overridepublic int compare(Cat o1, Cat o2) {Cat c1 = (Cat)o1;Cat c2 = (Cat)o2;if(c1.getHeight() > c2.getHeight()) return 1;else if(c1.getHeight() < c2.getHeight()) return -1;return 0;}}


package com.bjsxt.dp.strategy;public class CatWeightComparator implements Comparator {@Overridepublic int compare(Object o1, Object o2) {Cat c1 = (Cat)o1;Cat c2 = (Cat)o2;if(c1.getWeight() > c2.getWeight()) return -1;else if(c1.getHeight() < c2.getHeight()) return 1;return 0;}}


package com.bjsxt.dp.strategy;public class Test {public static void main(String[] args) {//int[] a = {9, 5, 3, 7, 1};Cat[] a = {new Cat(5, 5), new Cat(3, 3), new Cat(1, 1)};//Dog[] a = {new Dog(5), new Dog(3), new Dog(1)};//DataSorter.sort(a);java.util.Arrays.sort(a);DataSorter.p(a);}}







0 0
原创粉丝点击