Files
java-design-patterns/localization/zh/callback
Ilkka Seppälä 4108f86177 docs: Prepare for new website launch (#2149)
* Changed database implementation. Removed static objects.

* Fix Logs

* Fix 40 errors from checkstyle plugin run. 139 left))

* Fix CacheStore errors from checkstyle plugin 107 left

* Fix last errors in checkstyle.

* Fix sonar issues

* Fix issues in VALIDATE phase

* Fix Bug with mongo connection. Used "Try with resources"

* Add test

* Added docker-compose for mongo db. MongoDb db work fixed.

* Provided missing tests

* Comments to start Application with mongo.

* Fix some broken links

* Remove extra space

* Update filename

* Fix some links in localization folders

* Fix link

* Update frontmatters

* Work on patterns index page

* Work on index page

* Fixes according PR comments. Mainly Readme edits.

* fix frontmatter

* add missing png

* Update pattern index.md

* Add index.md for Chinese translation

* update image paths

* update circuit breaker image paths

* Update image paths for localizations

* add generated puml

* Add missing image

* Update img file extensions

* Update the rest of the EN and ZH patterns to conform with the new website

Co-authored-by: Victor Zalevskii <zvictormail@gmail.com>
2022-10-23 16:29:49 +03:00
..

title, category, language, tags
title category language tags
Callback Idiom zh
Reactive

目的

回调是一部分被当为参数来传递给其他代码的可执行代码,接收方的代码可以在一些方便的时候来调用它。

解释

真实世界例子

我们需要被通知当执行的任务结束时。我们为调用者传递一个回调方法然后等它调用通知我们。

通俗的讲

回调是一个用来传递给调用者的方法,它将在定义的时刻被调用。

维基百科说

在计算机编程中,回调又被称为“稍后调用”函数,可以是任何可执行的代码用来作为参数传递给其他代码;其它代码被期望在给定时间内调用回调方法。

编程示例

回调是一个只有一个方法的简单接口。

public interface Callback {

  void call();
}

下面我们定义一个任务它将在任务执行完成后执行回调。

public abstract class Task {

  final void executeWith(Callback callback) {
    execute();
    Optional.ofNullable(callback).ifPresent(Callback::call);
  }

  public abstract void execute();
}

public final class SimpleTask extends Task {

  private static final Logger LOGGER = getLogger(SimpleTask.class);

  @Override
  public void execute() {
    LOGGER.info("Perform some important activity and after call the callback method.");
  }
}

最后这里是我们如何执行一个任务然后接收一个回调当它完成时。

    var task = new SimpleTask();
    task.executeWith(() -> LOGGER.info("I'm done now."));

类图

alt text

适用性

使用回调模式当

  • 当一些同步或异步架构动作必须在一些定义好的活动执行后执行时。

Java例子

  • CyclicBarrier 构造函数可以接受回调,该回调将在每次障碍被触发时触发。