Java回调机制

-类图-

Java回调机制_第1张图片

-代码示例-

CallBackBody:

package com.test.callback;
 
 
public abstract class CallBackBody {
 
    void onSuccess(Object context) {
        System.out.println("onSuccess");
    }
 
    void onFailure(Object context) {
        System.out.println("onFailure");
    }
 
    abstract void execute(Object context) throws Exception;
}

CallBackTask:

package com.test.callback;
 
public class CallBackTask {
    private CallBackBody body;
 
    public CallBackTask(CallBackBody body) {
        this.body = body;
    }
 
    protected void start(final Object context) {
        final Thread t = new Thread(new Runnable() {
            public void run() {
                try {
                    body.execute(context);
                } catch (Exception e) {
                    e.printStackTrace();
                    body.onFailure(context);
                }
                body.onSuccess(context);
            }
        });
        t.start();
    }
}

CallBackApp:

package com.test.callback;
 
 
public class CallBackApp {
 
    public static void main(String[] args) {
 
        System.out.println("准备开始执行异步任务...");
 
        final Object context = "上下文信息";
 
        new CallBackTask(new CallBackBody() {
            @Override
            void execute(Object context) throws Exception {
                System.out.println("\n正在执行耗时操作...");
                System.out.println(context);
                Thread.sleep(5000);
                System.out.println("\n执行完成!");
            }
 
            void onSuccess(Object context) {
                System.out.println("\n成功后的回调函数...");
                System.out.println(context);
            }
 
            void onFailure(Object context) {
                System.out.println("\n失败后的回调函数...");
                System.out.println(context);
            }
        }).start(context);
 
        System.out.println("\n异步任务已经开始,请等待完成...");
    }
}


你可能感兴趣的:(Java回调)