java写一个回掉函数

public class CallbackExample1 {
    private interface Responser {
        void onSuccess(String data);
        void onFailed(String prompt);
    }
    private static String doSomething() {
        try {
            System.out.println("开始操作doSomething...");
            //模拟耗时操作(如网络请求),操作正常返回"Success","Success"表示有效的数据
            Thread.sleep(5000);
            return "Success";
        } catch (InterruptedException ex) {
            System.out.println("InterruptedException...");
            //操作出现问题返回"Failed","Failed"包含错误提示,如错误码等
            return "Failed";
        }
    }
    //使用回调函数完成操作
    private static void callbackDoSomething(Responser responser) {
        try {
            System.out.println("开始操作callbackDoSomething...");
            Thread.sleep(5000);
            responser.onSuccess("Success");
        } catch (InterruptedException ex) {
            System.out.println("InterruptedException2...");
            responser.onFailed("Failed");
        }
    }
    public static void main(String[] args) {
        System.out.println("正常模式 ------ " + doSomething());
        callbackDoSomething(new Responser() {
            @Override
            public void onSuccess(String data) {
                System.out.println("回调模式 ------ " + data);
            }

            @Override
            public void onFailed(String prompt) {
                System.out.println("错误提示:" + prompt);
            }

        });
    }
}

猜你喜欢

转载自blog.csdn.net/qq_39822451/article/details/89494883