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的回调都差不多。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值