接口的好处
①程序的耦合度降低;
②更自然的使用多态;
③设计与实现完全分离;
④更容易搭建程序框架;
⑤更容易更换具体实现;
实例源码:
对一组包含姓名、年龄、性别、分数的学生数组进行排序,分别按年龄、分数、姓名进行三种排序。
public class TestStudentSort {
public static void main(String[] args) {
Student st = new Student();
Student[] stus = st.initData();
SortTool tool = new SortTool(stus);
tool.print();
Student.rule = SortConfig.AGE_SORT;
tool.mySort();
tool.print();
Student.rule = SortConfig.SCORE_SORT;
tool.mySort();
tool.print();
Student.rule = SortConfig.NAME_SORT;
tool.mySort();
tool.print();
}
}
// ② 接口使用者 - 调用(实际执行了接口回调 - compareTo)
class SortTool {
Student[] s;
public SortTool() {}
public SortTool(Student[] ss) {
this.s = ss;
}
public void mySort () {
java.util.Arrays.sort(this.s);
}
public void print () {
if (Student.rule == SortConfig.AGE_SORT) {
System.out.println("年龄排序:");
traversal();
} else if (Student.rule == SortConfig.SCORE_SORT) {
System.out.println("分数排序:");
traversal();
} else if (Student.rule == SortConfig.NAME_SORT) {
System.out.println("名字排序:");
traversal();
} else {
System.out.println("未曾排序:");
traversal();
}
}
public void traversal () {
for (Student student : this.s) {
System.out.println("name:" + student.name + ", sex:" + student.sex + ", age:" + student.age + ", score:" + student.score);
}
System.out.println();
}
}
// ① 约定:接口/标准 java.util.Arrays.sort() 中实现了 Comparable 接口的 compareTo
// ① 约定:新增的,排序依据————未来是在单独的接口文件中 public interface 定义
interface SortConfig {
int AGE_SORT = 1; // 年龄
int SCORE_SORT = 2; // 分数
int NAME_SORT = 3; // 名字首字母 (临时起意加个规则,发现改动很少即可实现)
}
// ② 接口实现者 - 实现接口中需要覆盖的方法
class Student implements Comparable<Student> {
static int rule;
String name;
int age;
String sex;
double score;
public Student() {
super();
}
public Student(String name, int age, String sex, double score) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.score = score;
}
// 必要的初始化
public Student[] initData () {
Student[] ss = new Student[] {
new Student("cuee", 22, "女", 85.0),
new Student("aibi", 20, "男", 75.0),
new Student("emmm", 21, "女", 95.0),
new Student("bule", 25, "男", 55.0),
new Student("didi", 28, "男", 65.0),
};
return ss;
}
@Override
public int compareTo(Student o) {
// 0 不排序,1 升序,-1 降序
if (Student.rule == SortConfig.AGE_SORT) {
if (this.age > o.age) {
return 1;
} else if (this.age < o.age){
return -1;
} else {
return 0;
}
} else if (Student.rule == SortConfig.SCORE_SORT) {
if (this.score > o.score) {
return 1;
} else if (this.score < o.score){
return -1;
} else {
return 0;
}
} else if (Student.rule == SortConfig.NAME_SORT) {
if (this.name.charAt(0) > o.name.charAt(0)) {
return 1;
} else if (this.name.charAt(0) < o.name.charAt(0)){
return -1;
} else {
return 0;
}
} else {
return 0;
}
}
}
输出: