在Java講明白 回調函數Callback的來龍去脈(一)中,用Java講解了回調函數到底是個什麼玩意兒,但是真正使用Java寫回調函數的時候是通過接口去完成的。
現在我們又提一個需求,要求Github除了能回調Programmer的方法以外,還要求他能回調Student類的函數。
讓我們看看之前的Github類的代碼:
public class Github {
public void push(Programmer p ){
System.out.println("git push");
p.recordToday();
}
}
發現問題沒有,Github按照之前的方式,只能傳入Programmer類,現在咋解決呢,有兩種方式 第一種當然就是函數重載啦,再寫一個push函數 like so:
public void push(Student s )
這種方式當然可以啦,不過用接口 個人覺得更好,不然之後再來一個teacher類 是不是又要繼續重載一個接受teacher類函數?
ok,接口終於要登場了:
定義一個RecodeInterface 的接口:
public interface RecodeInterface {
public void recode();
}
接口裏定義一個recode()方法。
對於Programmer類,代碼如下:
public class Programmer {
public void code(){
System.out.println("coding");
new Github().push(new ProgrammerRecordToday());
}
public class ProgrammerRecordToday implements RecodeInterface{
@Override
public void recode() {
System.out.println("Programmer done " + new Date());
}
}
}
這裏有一個ProgrammerRecordToday的內部類,其實現了RecodeInterface接口。
再看一下Student類的代碼:
public class Student {
public void code(){
System.out.println("coding");
new Github().push(new StudentRecodeToday());
}
public class StudentRecodeToday implements RecodeInterface{
@Override
public void recode() {
System.out.println("Student done "+ new Date());
}
}
}
道理一樣,有一個StudentRecodeToday內部類,實現了RecodeInterface接口。
接下來是Github類:
public class Github {
public void push(RecodeInterface r ){
System.out.println("git push");
r.recode();
}
}
現在Github的push方法接受RecodeInterface 接口,所以兩個類的內部類都可以被push方法接收。
這樣一來就通過接口的形式完成了回調。
代碼我放在github上了:
https://github.com/zkuestc/CallbackDemo