用Java讲明白 回调函数Callback的来龙去脉(二)

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章