接口回调

1、首先有一个接口CallBack,接口中有个Operate方法。
2、A类实现了CallBack接口,并重写Operate方法。
3、B类中有一个方法,且这个方法有个参数为CallBack类型。
4、A类拥有B类的引用,这时在A类中就可以执行B类中的方法,在A类中执行B类中包含CallBack参数的方法,这个参数为A类自身的引用,那么就可以在B类中回调A类中的Operate方法了。

示例代码如下

public interface CallBack {

    void solve(String result);
}
public class A implements CallBack{

    private B b;
    public A(B b) {
        this.b = b;
    }
    public void askQuestion(final String question){
        doOtherSomething();
        new Thread( new Runnable(){

            @Override
            public void run() {
                b.solveQuestion(A.this, question);
            }

        }).start();
        doOtherSomething();
    }

    private void doOtherSomething() {
        for (int i = 0; i < 50; i++) {
            System.out.println("此时我还在做别的事情  "+i);
        }
    }
    @Override
    public void solve(String result) {
        System.out.println(result);
    }

}
public class B {

    public void solveQuestion(CallBack callback,String question){
        callback.solve("hello world!");
    }
}
public class Test {

    public static void main(String[] args) {
        B b = new B();
        A a = new A(b);
        a.askQuestion("学一门新的语言最先写什么");
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
接口回调是一种常见的编程模式,用于实现程序之间的通信和交互。在Python,可以通过函数或者方法来实现接口回调。 如果使用函数来实现接口回调,可以将一个函数作为参数传递给另一个函数或者的方法,然后在适当的时候调用这个函数来进行回调操作。 示例代码如下: ```python def callback_function(arg1, arg2): # 执行回调操作 print("Callback function called with arguments:", arg1, arg2) def perform_operation(callback): # 进行一些操作 result = 42 # 调用回调函数 callback("arg1", "arg2") # 使用回调函数 perform_operation(callback_function) ``` 上述代码,`perform_operation` 函数接收一个回调函数作为参数,并在适当的时候调用这个回调函数。在这个例子,我们调用 `perform_operation` 函数时会执行回调函数 `callback_function`,并传递两个参数 `"arg1"` 和 `"arg2"`。 如果使用方法来实现接口回调,可以定义一个接口,其包含一个或多个方法,然后创建一个实现接口,并将其实例传递给另一个的方法进行回调操作。 示例代码如下: ```python class CallbackInterface: def callback_method(self, arg1, arg2): # 执行回调操作 print("Callback method called with arguments:", arg1, arg2) class PerformOperation: def __init__(self, callback): self.callback = callback def perform_operation(self): # 进行一些操作 result = 42 # 调用回调方法 self.callback.callback_method("arg1", "arg2") # 使用回调方法 callback_instance = CallbackInterface() perform_operation = PerformOperation(callback_instance) perform_operation.perform_operation() ``` 上述代码,`CallbackInterface` 定义了一个回调方法 `callback_method`。`PerformOperation` 接收一个实现了 `CallbackInterface` 接口的对象作为参数,并在适当的时候调用该对象的回调方法。 无论是使用函数还是方法来实现接口回调,关键在于正确地传递回调函数或者实现回调接口的对象,并在适当的时候进行调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值