一般来说分为以下几步:
- 声明回调函数的统一接口interface A,包含方法callback();
- 在调用类caller内将该接口设置为私有成员private A XXX;
- 在caller内提供实现A接口的public方法(将外部该接口的实现类通过形参传入caller的XXX);
- caller的某个方法dosth()中会用到XXX.callback()方法;
- 在caller的实例中,先实现A接口,后调用dosth()方法;
网上流行的例子:
- //回调函数接口及方法
- 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);
- }
- }