学习Java第十八天--接口之接口回调

接口回调的原理、接口回调的代码展现、接口的好处

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();
	}

}

//1.接口/标准
interface USB{
	//服务方法(做什么,由实现者指定),服务的背后,必须遵照USB宽、高、深度、金属导线做一模一样的设计
	void servive();
}

//2.接口的使用者
class Computer{
	//使用USB接口
	USB usb;//new XXX()
	
	//开机
	public void on(USB usb) {
		this.usb = usb;
	}
	
	public void executeUSB() {
		usb.servive();//调用的接口中定义的方法(抽象方法)
	}
}

//3.接口的实现者
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> {

	/*
	 * 比较的方法
	 * this与传入的stu对象进行比较
	 * @param stu 另一个学生对象
	 * @return 标准:正数 负数 零
	 * 负数:this靠前,stu靠后
	 * 正数:this靠后,stu靠前
	 * 零:不变
	 * */
	public int compareTo(T stu);//Student 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),
		};
		//java.util.Arrays.sort(students);
		
		
		//工具调用者
		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 接口的好处

  • 程序的耦合度降低;
  • 更自然的使用多态;
  • 设计与实现完全分离;
  • 更容易搭建程序框架;
  • 更容易更换具体实现;
发布了34 篇原创文章 · 获赞 7 · 访问量 1297

猜你喜欢

转载自blog.csdn.net/weixin_44257082/article/details/104523281