Java回调函数

所谓的回调,就是程序员A写了一段程序(程序a),其中预留有回调函数接口,并封装好了该程序。程序员B要让a调用自己的程序b中的一个方法,于是,他通过a中的接口回调自己b中的方法。

1.  首先定义一个类Caller,按照上面的定义就是程序员A写的程序a,这个类里面保存一个接口引用。

public class Caller {  
    private MyCallInterface callInterface;  
      
    public Caller() {  
    }  
      
    public void setCallFunc(MyCallInterface callInterface) {  
        this.callInterface = callInterface;  
    }  
      
    public void call() {  
        callInterface.printName();  
    }  
}

2.  当然需要接口的定义,为了方便程序员B根据我的定义编写程序实现接口。

public interface MyCallInterface {  
    public void  printName();  
}

3.  第三是定义程序员B写的程序b

public class Client implements MyCallInterface {  
  
    @Override  
    public void printName() {  
        System.out.println("This is the client printName method");  
    }  
}

4.  测试如下

public class Test {  
    public static void main(String[] args) {  
        Caller caller = new Caller();  
        caller.setCallFunc(new Client());  
        caller.call();  
    }  
}

5.  在测试方法中直接使用匿名类,省去第3步。

public class Test {  
    public static void main(String[] args) {  
        Caller caller = new Caller();  
//      caller.setCallFunc(new Client());  
        caller.setCallFunc(new MyCallInterface() {  
            public void printName() {  
                System.out.println("This is the client printName method");  
            }  
        });  
        caller.call();  
    }  
}

我是天王盖地虎的分割线                                                             

 

 

参考:http://blog.csdn.net/allen_zhao_2012/article/details/8056665

posted @ 2014-09-23 15:42  我爱物联网  阅读(3510)  评论(3编辑  收藏  举报
AmazingCounters.com