java和javascript中的回调函数

王朝学院·作者佚名  2009-01-16
窄屏简体版  字體: 小  |  中  |  大  |  超大  

先看看java中的回调函数,java中很多模式和它类似,有访问者,观察者等模式。ioc等也有这个类似的原理。

Java代码

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("回调后.....");

}

}

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("回调后.....");

}

} 输出结果为:

Java代码

回调前.....

正在执行....

回调后.....

回调前.....

正在执行....

回调后.....这里充分的体现了不是我来调用你,而是你来调用我。

这里的我就是“doExecute”,你就是"execute"

回调可以用在哪些地方呢?

1,比如著名的ioc的事务处理就是这样的,每个方法的事务处理都是一样的,都是些开始一个事务,用try包住,等等,所以就可以不管他们,变的只是要执行方法的不同,比如存储,删除,查询什么的。

2,可以减少写类,一个接口,可以有很多的实现类,在回调里面,就成了匿名的了。著名的jive里面DatabaseObjectFactory 就是这个用法。

Java代码

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);

}

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里面的:

Js代码

function Test()

{

var self=this;

this.func1=function()

{

self.test2(function (){ alert('正在执行');})

}

}

Test.prototype.test2=function(func)

{

alert("回调前做些东西");

if(func)

func();

alert("回调后做些东西");

}

function Test()

{

var self=this;

this.func1=function()

{

self.test2(function (){ alert('正在执行');})

}

}

Test.prototype.test2=function(func)

{

alert("回调前做些东西");

if(func)

func();

alert("回调后做些东西");

}

然后,在html里面:

Html代码

<html>

<head>

<script type=text/javascript src="1.js">

</script>

<script>

new Test().func1();

</script>

</head>

<body>

</body>

</html>

<html>

<head>

<script type=text/javascript src="1.js">

</script>

<script>

new Test().func1();

</script>

</head>

<body>

</body>

</html>

java和javascript的回调都差不多。

声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航