想问什么?下面也是一个接口回调的例子
// templatetest2.java
package com.designpattern.template;
/**
* 回调接口
*/
interface testtemplatecallback {
object dosomething();
}
class template2 {
/**
* 执行业务逻辑的方法,参数类型为接口对象
*
* @param callback:testtemplatecallback接口对象
*/
public void execute(testtemplatecallback callback) {
try {
system.out.println("事务开始。。。");
system.out.println("开始执行业务逻辑。。。");
callback.dosomething();
system.out.println("业务逻辑执行成功,提交事务");
} catch (exception e) {
system.out.println("出现错误,回滚");
e.printstacktrace();
}
}
}
public class templatetest2 {
public void insert(final string msg) {
template2 t = new template2();
// 匿名内部类重写方法
t.execute(new testtemplatecallback() {
public object dosomething() {
// 事务出错代码
// int i = 1 / 0;
system.out.println("插入数据:" + msg);
return null;
}
});
}
public static void main(string[] args) {
templatetest2 t = new templatetest2();
t.insert("hello");
}
}
在这里申明一个接口,里面有个方法dosomething()。template2 这个类中的execute()方法用来执行事务,其中有个参数:execute(testtemplatecallback callback),参数类型为之前定义的接口对象,然后就可以利用这个对象来调用dosomething()方法。但是dosomething()方法具体的操作内容在哪呢?它在templatetest2的insert()方法里面,这里在templatetest2类中定义一个insert()方法,接着申明一个template2对象t,当执行t.execute()方法的时候,这时我们写个匿名类来当传入参数,这匿名类就是之前的接口,在匿名类中重写dosomething()方法就可以实现具体操作了。
实际的列子可以参考spring源码中的jdbctemplate类。