Java学习打卡Day19

知识回顾

回调原理

先有接口的使用者,后有接口的实现者
(1)标准:接口
(2)工具:接口的使用者
(3)接口的实现者:程序员
(4)工具的调用者:程序员

接口回调

  1. Usb案例
public class TestUsb {

	public static void main(String[] args) {

		Computer computer = new Computer();
		//4、使用工具
		computer.on(new Fan(), new Light(), new Disk());
	}
}
//2、接口的使用者(工具)
class Computer{

	public void on(Usb u1 , Usb u2 , Usb u3){

		System.out.println("电脑开机……");
		u1.service();
		u2.service();
		u3.service();
	}
}
//1、接口、标准
interface Usb{
	public abstract void service();
}
//3、接口的实现者
class Fan implements Usb{
	public void service(){
		System.out.println("旋转……");
	}
}
class Light implements Usb{
	public void service(){
		System.out.println("照明……");
	}
}
class Disk implements Usb{
	public void service(){
		System.out.println("传输数据……");
	}
}

一、先有USB接口标准
二、再有利用标准的生产出的工具,如:computer,工具可以在有实现者之前出来,是因为有标准,所有的实现者必须根据标准设计
三、根据不同的需求,设计不同的接口的实现者Fan、Light、Disk
四、最后,使用工具

  1. 哥德巴赫猜想案列
public class TestGoldBach{

	public static void main(String[] args) {
		
		//4、使用工具
		checkGoldBach(10 , new EngineerAsIsPrime());
	}
	
	//2、工具
	public static void checkGoldBach(int num , MathTool tool) {

		for(int i = 2 ; i < num/2 ; i++) {
			if( tool.isPrime(i) && tool.isPrime(num-i)) {
				System.out.println(i +"\t"+ (num-i));
			}
		}
	}
}
//1、标准
interface MathTool{
	public abstract boolean isPrime(int n);
}


//3、实现类
class EngineerAsIsPrime implements MathTool  {
	public boolean isPrime(int n) {
		for(int i = 2 ; i < n; i++) {
			if(n % i == 0) {
				return false;
			}
		}
		return true;
	}
}
  1. 排序
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",98.0) , new Student("annie",19,"female",100.0)};
		
		//4、工具调用者
		Tool.sort(students);
		for (int i = 0; i < students.length; i++) 
			System.out.println(students[i].name +"\t"+ students[i].score);
	}
}
//1、标准
public interface Comparable<T> {
	public int compareTo(T stu) ;//Student stu
}
//3、实现者
class Student implements Comparable<Student>{
	String name;
	int age;
	String sex;
	double score;
	public Student(String name, int age, String sex, double score) {
		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;
	}
}
//2、工具
public class Tool {
	public static void sort(Student[] stus) {
		for(int i = 0 ;  i < stus.length - 1 ; i++) {
			Comparable currentStu= (Comparable)stus[i];
			int n = currentStu.compareTo(stus[i+1]);
			if(n > 0) {
				Student temp = stus[0];
				stus[0] = stus[1];
				stus[1] = temp;
			}
		}
	}
}

打卡

Life isn’t about finding yourself. Life is about creating yourself.
人生并不是关乎找到自我,而是关乎创造自我

发布了33 篇原创文章 · 获赞 3 · 访问量 917

猜你喜欢

转载自blog.csdn.net/qq_44952731/article/details/104545778