所謂的回調,就是程序員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