回调函数定义:
从维基百科上面摘抄定义:
在计算机程序设计中,回调函数,或简称回调,是指通过函数参数传递到其它代码的,某一块可执行代码的引用。这一设计允许了底层代码调用在高层定义的子程序。
从定义上看,允许底层代码调用高层定义的子程序,可以理解为将一个对象以参数的形式传递进来,然后调用其中的方法,当然高层次的话,则要求该对象是接口或抽象类(总之,需要拥有抽象方法),当调用该传入的对象的方法时,就会回调该对象更高层次的方法。
在整个过程中,只有在传入的参数调用其自身的方法时,就是一个回调函数了。
就比如,我在图中画的这个modelMethod
方法,它的参数就是一个接口,在其中调用接口的方法(详情请继续往下翻,有完整代码!)
那么问题就在于,这里定义了一个匿名对象,就是实例化了一个接口,在其中实现了接口中的方法。以整个匿名对象作为参数传递进去,在模板方法中调用的方法就是它自己实现的那个方法了。
上代码:
package org.feng.call;
/**
* 模板方法+回调函数
* @author Feng
* 2018年11月26日上午11:13:39
*/
public class CallBackDemo {
/**
* 测试:模板方法+回调函数+匿名内部类。
* @param args
*/
public static void main(String[] args) {
test1();
test2();
}
// 测试方式1:使用匿名
public static void test1() {
// 注入接口的匿名实例。
new ModelMethod().modelMethod(new TestMethod() {
// 实现接口TestMethod中的test方法。
@Override
public void test() {
System.out.println("我是匿名类的test()方法,我被回调函数调用了!");
}
});
}
// 测试方式2:使用接口的实现类
public static void test2() {
ModelMethod modelMethod = new ModelMethod();
modelMethod.modelMethod(new TestMethodImpl());
}
}
/**
* 模板方法类。
* @author Feng
* 2018年11月26日下午12:45:00
*/
class ModelMethod{
/**
* 定义:模板方法!
*/
public final void modelMethod(TestMethod method) {
before();
// 调用接口中的方法。
method.test();
after();
}
// 设置不可见。
private void before() {
System.out.println("执行在 test() 之前");
}
// 设置不可见。
private void after() {
System.out.println("执行在 test() 之后");
}
}
/**定义接口!*/
interface TestMethod{
void test();
}
class TestMethodImpl implements TestMethod {
@Override
public void test() {
System.out.println("我是TestMethod实现类中的test()!!");
}
}
测试结果:
执行在 test() 之前
我是匿名类的test()方法,我被回调函数调用了!
执行在 test() 之后
执行在 test() 之前
我是TestMethod实现类中的test()!!
执行在 test() 之后