简体   繁体   English

什么是Java中的回调接口?

[英]What is a call back interface in Java?

This code snippet for the interface SetObserver is taken from Effective Java (Avoid Excessive Synchronization Item 67) 接口SetObserver的此代码段取自Effective Java(避免过多的同步项67)

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

And the SetObserver is passed to addObserver() and removeObserver method 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 . Bloch将SetObserver<E>接口称为回调接口 When is a interface called an call back interface in Java? 什么是Java中称为回调接口的接口?

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. 回调机制可以用不同的语言实现:C#除了回调接口外还有委托和事件,C有可以通过指针传递的函数,Objective C有委托协议,等等。 But the main idea is always the same: the caller passes a piece of code to be called upon occurrence of a certain event. 但主要思想始终相同:调用者传递一段代码,以便在发生某个事件时调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM