General frameworks have interfaces for setting callback/hook. When an event occurs in the framework, the callback set by the user will be called. For example, the following is a simple example:
public class CallbackTest {
public static void main(String args[]) throws Exception {
// 1. 实例化一个回调逻辑.
Callback userCallback = new Callback() {
@Override
public void call(String message) {
System.out.println("Call from framework, message: " + message);
}
};
// 2. 初始化一个假象的框架, 并设置用户的回调接口.
SomeFramework framework = new SomeFramework(userCallback);
// 3. 启动框架
framework.start();
Thread.sleep(5000);
}
interface Callback {
void call(String message);
}
static class SomeFramework implements Runnable {
Callback userCallback;
public SomeFramework(Callback userCallback) {
this.userCallback = userCallback;
}
public void start() {
new Thread(this).start();
}
@Override
public void run() {
try {
Thread.sleep(3000);
somethingHappened();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 4. 当框架内的状态变化时或者是发生了某个事件时, 就调用用户设置的回调接口.
private void somethingHappened() {
userCallback.call("Something happended!");
}
}
}
In fact, it is a bit like event-driven or observer mode. The framework saves the user's callback interface, and this interface serves as a bridge for communication between the framework and user code. When the framework detects that an event occurs, it will be notified through this callback interface. User code.
Promise...promise...I suggest you take a look at the observer pattern
For example, if you add an action listener to the button
button.addActionListener(new ActionListener() {
public actionPerformed(ActionEvent e) {
// do something
}
});
It is agreed that the action listener will be triggered when the button is pressed, so when you add it, you already know when it will be called. Although you don't know the specific point in time, you know that if something happens, it will be called.
General frameworks have interfaces for setting callback/hook. When an event occurs in the framework, the callback set by the user will be called.
For example, the following is a simple example:
In fact, it is a bit like event-driven or observer mode. The framework saves the user's callback interface, and this interface serves as a bridge for communication between the framework and user code. When the framework detects that an event occurs, it will be notified through this callback interface. User code.
Promise...promise...I suggest you take a look at the observer pattern
For example, if you add an action listener to the button
It is agreed that the action listener will be triggered when the button is pressed, so when you add it, you already know when it will be called. Although you don't know the specific point in time, you know that if something happens, it will be called.