java和javascript中的回调函数
先看看java中的回调函数,java中很多模式和它类似,有访问者,观察者等模式。ioc等也有这个类似的原理。
public class Test {/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new Test().doExecute(new CallBack(){ public void execute() { System.out.println("正在执行...."); } });}private void doExecute(CallBack callBack) { System.out.println("回调前....."); callBack.execute(); System.out.println("回调后.....");}} 输出结果为:
回调前.....正在执行....回调后.....这里充分的体现了不是我来调用你,而是你来调用我。
这里的我就是“doExecute”,你就是"execute"
回调可以用在哪些地方呢?
1,比如著名的ioc的事务处理就是这样的,每个方法的事务处理都是一样的,都是些开始一个事务,用try包住,等等,所以就可以不管他们,变的只是要执行方法的不同,比如存储,删除,查询什么的。
2,可以减少写类,一个接口,可以有很多的实现类,在回调里面,就成了匿名的了。著名的jive里面DatabaseObjectFactory 就是这个用法。
interface DatabaseObjectFactory { /** * Returns the object associated with id or null if the * object could not be loaded. * * @param id the id of the object to load. * @return the object specified by id or null if it could not * be loaded. */ public Object loadObject(long id); }
外面调用的根据id不同产生任何你想要的对象。
在看看javascript里面的:
function Test(){var self=this;this.func1=function(){self.test2(function (){ alert('正在执行');})}}Test.prototype.test2=function(func){alert("回调前做些东西");if(func) func(); alert("回调后做些东西");} 然后,在html里面:
<html> <head> <script type=text/javascript src="1.js"> </script> <script> new Test().func1(); </script> </head> <body> </body></html> java和javascript的回调都差不多。
页:
[1]