|
9 | 9 | ---
|
10 | 10 |
|
11 | 11 | ## Intent
|
12 |
| -Callback is a piece of executable code that is passed as an |
13 |
| -argument to other code, which is expected to call back (execute) the argument |
14 |
| -at some convenient time. |
| 12 | +Callback is a piece of executable code that is passed as an argument to other code, which is expected to call back |
| 13 | +(execute) the argument at some convenient time. |
| 14 | + |
| 15 | +## Explanation |
| 16 | + |
| 17 | +Real world example |
| 18 | + |
| 19 | +> We need to be notified after executing task has finished. We pass a callback method for the executor and wait for it to call back on us. |
| 20 | +
|
| 21 | +In plain words |
| 22 | + |
| 23 | +> Callback is a method passed to the executor which will be called at defined moment. |
| 24 | +
|
| 25 | +Wikipedia says |
| 26 | + |
| 27 | +> In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time. |
| 28 | +
|
| 29 | +**Programmatic Example** |
| 30 | + |
| 31 | +Callback is a simple interface with single method. |
| 32 | + |
| 33 | +```java |
| 34 | +public interface Callback { |
| 35 | + |
| 36 | + void call(); |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +Next we define a task that will execute the callback after the task execution has finished. |
| 41 | + |
| 42 | +```java |
| 43 | +public abstract class Task { |
| 44 | + |
| 45 | + final void executeWith(Callback callback) { |
| 46 | + execute(); |
| 47 | + Optional.ofNullable(callback).ifPresent(Callback::call); |
| 48 | + } |
| 49 | + |
| 50 | + public abstract void execute(); |
| 51 | +} |
| 52 | + |
| 53 | +public final class SimpleTask extends Task { |
| 54 | + |
| 55 | + private static final Logger LOGGER = getLogger(SimpleTask.class); |
| 56 | + |
| 57 | + @Override |
| 58 | + public void execute() { |
| 59 | + LOGGER.info("Perform some important activity and after call the callback method."); |
| 60 | + } |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +Finally here's how we execute a task and receive a callback when it's finished. |
| 65 | + |
| 66 | +```java |
| 67 | + var task = new SimpleTask(); |
| 68 | + task.executeWith(() -> LOGGER.info("I'm done now.")); |
| 69 | +``` |
15 | 70 |
|
16 | 71 | ## Class diagram
|
17 | 72 | 
|
|
0 commit comments