Java-马士兵设计模式学习笔记-策略模式-模拟Comparable接口
一、情况
1.目标:要在专门用于排序数据的DataSorter.java中实现对所有A类,B类,C类,D类等等的排序
2.初步想法:DataSorter.java的代码如下
public class DataSorter { public static void sort(A a){ } public static void sort(B a){ } public static void sort(C c){ } //................... }
3.这样会造成DataSorter的可扩展性差,要支持对新类的排序时,要修改代码。更好的思路是:既然DataSorter是要根据不同的类的采取不同的方法实现排序,那么具体实现排序的方法交由子类去实现,且都实现同一个接口Comparable,那么DataSorter只需对Comparable排序,而无需理会具体要排序的是什么类(多态)
4.有如下几个类:
(1)DataSorter.java
(2)接口Comparable.java
(3)Student.java
(4)Teacher.java
(5)Test.java
5.代码如下:
(1)DataSorter.java
public class DataSorter { public static void sort(Comparable [] a) { int index; //保存每次比较,最大值的下标; for(int i = 1; i < a.length; i++){ //控制外循环次数 index = 0; for(int j = 1; j <= a.length - i ; j++){ if(a[j].compareTo(a[index]) == 1){ index = j; } } swap(a, index, a.length -i); } } private static void swap(Comparable[] a, int x, int y) { Comparable tmp = a[x]; a[x] = a[y]; a[y] = tmp; } //输出数组元素 public static void show(Comparable[] a) { for(int i = 0; i < a.length; i++){ System.out.println(a[i]); } } }
(2)Comparable.java
public interface Comparable<T> { public int compareTo(T o); }
(3)Teacher.java
public class Teacher implements Comparable<Teacher> { private int title; public Teacher(int title) { super(); this.title = title; } public int getTitle() { return title; } public void setTitle(int title) { this.title = title; } @Override public int compareTo(Teacher o) { if(this.title > o.getTitle()){ return 1; }else if(this.title == o.getTitle()){ return 0; }else{ return -1; } } @Override public String toString() { return "teacher--" +title+" "; } }
(4)Student.java
public class Student implements Comparable<Student> { private int mark; public int getMark() { return mark; } public void setMark(int mark) { this.mark = mark; } public Student(int mark) { super(); this.mark = mark; } @Override public String toString() { return "student" +mark+" "; } @Override public int compareTo(Student o) { if(this.mark > o.getMark()){ return 1; }else if(this.mark == o.getMark()){ return 0; }else{ return -1; } } }
(5)Test.java
public class Test { public static void main(String[] args) { //int [] a = {9,2,1,8,0,3}; Student [] ss = {new Student(59),new Student(30),new Student(90)}; DataSorter.sort(ss); DataSorter.show(ss); Teacher [] ts = {new Teacher(10),new Teacher(3),new Teacher(12)}; DataSorter.sort(ts); DataSorter.show(ts); } }
测试结果
You can do anything you set your mind to, man!