Java 中的回调接口是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11577695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:39:20  来源:igfitidea点击:

What is a call back interface in Java?

java

提问by Geek

This code snippet for the interface SetObserver is taken from Effective Java (Avoid Excessive Synchronization Item 67)

这个接口 SetObserver 的代码片段取自Effective Java (Avoid Excessive Synchronization Item 67)

public interface SetObserver<E> {
// Invoked when an element is added to the observable set
void added(ObservableSet<E> set, E element);
}

And the SetObserveris passed to addObserver()and removeObservermethod as given below :

并且SetObserver传递给addObserver()removeObserver方法如下:

// Broken - invokes alien method from synchronized block!
public class ObservableSet<E> extends ForwardingSet<E> {
  public ObservableSet(Set<E> set) {
    super(set);
  }

  private final List<SetObserver<E>> observers =
      new ArrayList<SetObserver<E>>();

  public void addObserver(SetObserver<E> observer) {
    synchronized (observers) {
      observers.add(observer);
    }
  }



  public boolean removeObserver(SetObserver<E> observer) {
    synchronized (observers) {
      return observers.remove(observer);
    }
  }



  private void notifyElementAdded(E element) {
    synchronized (observers) {
      for (SetObserver<E> observer : observers)
        observer.added(this, element);
    }
  }

Bloch refers to the SetObserver<E>interface as a call back interface. When is a interface called an call back interface in Java?

Bloch 将该SetObserver<E>接口称为回调接口。什么时候接口在Java中称为回调接口?

回答by dasblinkenlight

A general requirement for an interface to be a "callback interface" is that the interface provides a way for the callee to invoke the code inside the caller. The main idea is that the caller has a piece of code that needs to be executed when something happens in the code of another component. Callback interfaces provide a way to pass this code to the component being called: the caller implements an interface, and the callee invokes one of its methods.

接口作为“回调接口”的一般要求是接口为被调用者提供调用调用者内部代码的方法。主要思想是调用者有一段代码需要在另一个组件的代码中发生某些事情时执行。回调接口提供了一种将此代码传递给被调用组件的方法:调用者实现一个接口,被调用者调用它的一个方法。

The callback mechanism may be implemented differently in different languages: C# has delegates and events in addition to callback interfaces, C has functions that can be passed by pointer, Objective C has delegate protocols, and so on. But the main idea is always the same: the caller passes a piece of code to be called upon occurrence of a certain event.

回调机制在不同的语言中可能实现不同:C#除了回调接口还有委托和事件,C有可以通过指针传递的函数,Objective C有委托协议,等等。但主要思想始终是相同的:调用者传递一段代码,在某个事件发生时被调用。