- //回调函数接口及方法
- public interface ICallback {
- public void func();
- }
- //回调函数接口实现类
- public class ClassWithCallbackFunction implements ICallback{
- public ClassWithCallbackFunction() {
- }
- public void func(){
- System.out.println("cccccccccccccccccc");
- }
- }
- public class Caller {
- private ICallback callback; //私有接口成员
- public void setCallback(ICallback callback) {
- this.callback = callback; //接口成员的实现:从外部传入
- }
- public void doCallback() { //回调接口成员的方法
- callback.func();
- }
- }
- }
- public class MainClass {
- public MainClass() {
- }
- public static void main(String[] args) {
- Caller caller = new Caller();
- caller.setCallback(new ClassWithCallbackFunction() {
- public void func() {
- System.out.println("aaaaaaaaaa");
- }
- });
- caller.doCallback(); //实现回调
- }
- }
- //现实中是把doCallback()方法放在setCallback里调用,以上是为了说明回调原理
- public class Caller {
- ICallback callback;
- public void doCallback() {
- callback.func();
- }
- public void setCallback(ICallback callback) {
- this.callback = callback;
- doCallback();
- }
- }
另一个例子是JAVA排序的compare接口
- interface Compare {
- boolean lessThan(Object lhs, Object rhs);
- boolean lessThanOrEqual(Object lhs, Object rhs);
- }
- import java.util.*;
- public class SortVector extends Vector {
- private Compare compare; // 私有接口成员
- public SortVector(Compare comp) {
- compare = comp;
- }
- public void sort() {
- quickSort(0, size() - 1);
- }
- private void quickSort(int left, int right) {
- if(right > left) {
- Object o1 = elementAt(right);
- int i = left - 1;
- int j = right;
- while(true) {
- while(compare.lessThan(
- elementAt(++i), o1))
- ;
- while(j > 0)
- if(compare.lessThanOrEqual(
- elementAt(--j), o1))
- break;
- if(i >= j) break;
- swap(i, j);
- }
- swap(i , right);
- quickSort(left, i-1);
- quickSort(i+1, right);
- }
- }
- private void swap(int loc1, int loc2) {
- Object tmp = elementAt(loc1);
- setElementAt(elementAt(loc2), loc1);
- setElementAt(tmp, loc2);
- }
- }
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>