10.3 接口回调
10.3.1 什么是接口
接口的实现者 |
接口/标准 |
接口的使用者 |
U盘、USB风扇、充电线 |
USB |
电脑上的USB插口 |
public class TestUsbInterface {
public static void main(String[] args) {
Computer computer = new Computer();
USB MyFan = new Fan();
computer.on(MyFan);
computer.executeUSB();
USB MyUDisk = new UDisk();
computer.on(MyUDisk);
computer.executeUSB();
}
}
interface USB{
void servive();
}
class Computer{
USB usb;
public void on(USB usb) {
this.usb = usb;
}
public void executeUSB() {
usb.servive();
}
}
class Fan implements USB{
public void servive() {
System.out.println("通电--旋转");
}
}
class Lamp2 implements USB{
public void servive() {
System.out.println("通电--照明");
}
}
class UDisk implements USB{
public void servive() {
System.out.println("通电--读写数据");
}
}
10.3.2 回调原理
- 接口回调:先有接口的使用者,后有接口的实现者;
public interface Comparable<T> {
public int compareTo(T stu);
}
public class Tool {
public static void sort(Student[] stus) {
for(int j = 0; j < stus.length ; j++) {
for(int i = 0 ;i < stus.length - j - 1; i++) {
Comparable currentStu = (Comparable)stus[i];
int n = currentStu.compareTo(stus[i+1]);
if(n > 0) {
Student temp = stus[i];
stus[i] = stus[i+1];
stus[i+1] = temp;
}
}
}
}
}
public class TestCallback {
public static void main(String[] args) {
Student[] students = new Student[] {
new Student("tom",20,"male",99.0),
new Student("jack",21,"male",95.0),
new Student("alex",20,"male",100.0),
new Student("annie",19,"female",97.0),
};
Tool.sort(students);
for(int i = 0 ; i < students.length ; i++) {
System.err.println(students[i].name+"\t"+students[i].score);
}
}
}
class Student implements Comparable<Student>{
String name;
int age;
String sex;
double score;
public Student() {}
public Student(String name, int age, String sex, double score) {
super();
this.name = name;
this.age = age;
this.sex = sex;
this.score = score;
}
public int compareTo(Student stu) {
if(this.score > stu.score) {
return 1;
}else if(this.score < stu.score) {
return -1;
}
return 0;
}
}
10.4 接口的好处
- 程序的耦合度降低;
- 更自然的使用多态;
- 设计与实现完全分离;
- 更容易搭建程序框架;
- 更容易更换具体实现;