Classic use case of java interface callback

brief introduction:

  1. Understanding of interface callbacks and issues that need attention
  2. General routine usage of interface callback
  3. Simple usage of interface callback
  4. The meaning of interface callback

Introduction to interface callback:

Simply put, the interface callback is: the caller class A accesses the M method in the callee class B. The M method calls the method in class A after the execution is completed.

question?

How does the M method in class B access the method in class A? After clarifying this problem, I also understand the interface callback.

Let's write code based on a scenario description:

We use the download file method DownLoadFile() in the callee's Collee class in the caller's Caller class. After the download is complete, the Caller class must be notified that the file is loaded. At this time, the Caller class can access the resources just downloaded. Because the download takes time. The Caller class has other things to do. It can't wait for the download to complete before doing it. In this case, the download method must open a new thread to download.

General routine usage of interface callback

Code:

1. Interface and callback method:

/*
CallBackListener (回调监听接口)
用于回调的接口 (接口内的抽象方法用于监听被调用者返回的结果)
接口中有回调方:该回调方法是被调用者通过回调接口对象去访问调用者的方法.所以形参应该是被调用者返回给调用者结果的数据类型和参数个数。
*/
public interface CallBackListener {
    //发送消息给调用者
    public abstract void sendMessage2Caller(String msg);
}

2. Caller class:

/*
Caller :(调用者)
调用者在访问被调用者的方法前.必须将回调接口对象设置给被调用者.以方便被调用者使用接口回调对象访问自己.
*/
public class Caller {
    public static void main(String[] args) {
        //1.创建被调用者对象
        Callee callee = new Callee();

        //2.创建回调接口对象.
        CallBackListener cb = new CallBackListener() {

            @Override
            public void sendMessage2Caller(String msg) {
                //打印回调传递过来的结果
                System.out.println(msg);

            }
        };

        //3.必须将回调接口对象设置给被调用者
        callee.setCallBackListener(cb);

        //4.访问被调用者的下载文件方法.这个方法完成后被调用者会通过回调接口对象通知我们.
        callee.DownLoadFile();

        System.out.println("你下载真慢,我先去忙别的事了....");
    }
}

3. The callee class

/*
Callee(被调用者):
1.被调用者类中必须有回调接口类型的变量.
2.并且还要有给该变量赋值的setXxx()方法.
3.在可以给调用者返回结果的时候.拿着接口类型的变量调用接口的方法进行对调用者的访问.(因为接口类型的变量要执行的方法在调用者那里存在).
*/
public class Callee {
    //1.被调用者类中必须有 回调接口类型的变量.
    private CallBackListener cb;

    //2.并且还要有给该变量赋值的setXxx()方法.
    public void setCallBackListener(CallBackListener cb){
        this.cb = cb;
    }

    /**
    * 下载文件是非常耗时的工作.而调用者又需要在下载完成后读取下载的文件.
    * 所以当这个方法完成下载后应该立刻通知调用者.这个通知的动作就称之为回调.
    * @throws InterruptedException 
    */
    public void DownLoadFile(){
        //开启新的线程去下载.异步任务.
        new Thread(){
            public void run() {
                long start = System.currentTimeMillis();

                //使用睡眠模拟耗时工作.
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                long end = System.currentTimeMillis();

                //完成下载后通知调用者
                if(cb != null){
                    cb.sendMessage2Caller("下载完成,耗时:"+(end-start)/1000+"秒,你可以去访问资源了.");
                }
            };
        }.start();
    }
}

The running result is as follows:

Classic use case of java interface callback

5 seconds later

Classic use case of java interface callback

Simple usage of interface callback

Code:

1. Interface and callback method:

/*
CallBackListener (回调监听接口)
用于回调的接口 (接口内的抽象方法用于监听被调用者返回的结果)
接口中有回调方:该回调方法是被调用者通过回调接口对象去访问调用者的方法.所以形参应该是被调用者返回给调用者结果的数据类型和参数个数。
*/
public interface CallBackListener {
    //发送消息给调用者
    public abstract void sendMessage2Caller(String msg);
}

2. Caller class:

public class Caller {
    public static void main(String[] args) {
        //1.创建被调用者对象
        Callee callee = new Callee();
        //2.访问被调用者的下载文件方法.这个方法完成后被调用者会通过回调接口对象通知我们.
        //使用匿名内部类对象当做参数传递.更加简洁
        callee.DownLoadFile(new CallBackListener() {

            @Override
            public void sendMessage2Caller(String msg) {
                //打印回调传递过来的结果
                System.out.println(msg);
            }
        });

        System.out.println("你下载真慢,我先去忙别的事了....");
    }
}

3. The callee class

/**
* 下载文件是非常耗时的工作.而调用者又需要在下载完成后读取下载的文件.
* 所以当这个方法完成下载后应该立刻通知调用者.这个通知的动作就称之为回调.
* final CallBackListener cb 匿名内部类访问局部变量必须加final.
*/      
public class Callee {
    public void DownLoadFile(final CallBackListener cb){
        //开启新的线程去下载.异步任务.
        new Thread(){
            public void run() {
                long start = System.currentTimeMillis();

                //使用睡眠模拟耗时工作.
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                long end = System.currentTimeMillis();

                //完成下载后通知调用者
                if(cb != null){
                    cb.sendMessage2Caller("下载完成,耗时:"+(end-start)/1000+"秒,你可以去访问资源了.");
                }

            };
        }.start();
    }
}

The meaning of interface callback:

Through the above two cases, will you have a question. Why do you want to make an interface? Is it OK to replace the interface with a normal class?

Of course it is possible. The reason for using interface callbacks here is because interfaces are normative and flexible. Especially normative.

Code example:

1. The original interface is replaced by an abstract class, and the other two classes remain unchanged, which will not affect the running effect

public abstract class CallBackListener {
    //发送消息给调用者
    public abstract void sendMessage2Caller(String msg);
}

2. The original interface is replaced by a class, and the other two classes remain unchanged, which will not affect the running effect

public class CallBackListener {
    //发送消息给调用者
    public void sendMessage2Caller(String msg){

    };
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324779772&siteId=291194637