callback 模式之前在看 nodejs 的时候有很多应用,java 中本人没怎么用过
callback 即回调模式,举例来说,当方法 A 完成后自动触发方法 B,是一种异步实现
本文为 java 实现
package com.carl.callback;
public interface Callback {
public void call();
}
package com.carl.callback;
public abstract class Task {
public void executer(Callback callback) {
exec();
if (callback != null) {
callback.call();
}
}
abstract void exec();
}
package com.carl.callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SimpleTask extends Task {
private Logger LOGGER = LoggerFactory.getLogger(SimpleTask.class);
@Override
void exec() {
LOGGER.debug("simple task exec");
}
}
package com.carl.callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static Logger LOGGER = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
SimpleTask st = new SimpleTask();
// st.executer(new Callback() {
// @Override
// public void call() {
// LOGGER.debug("st executer");
// }
// });
st.executer(() -> { //java8 lambda调用
LOGGER.debug("st executer");
}
);
}
}
09:11:13.533 [main] DEBUG com.carl.callback.SimpleTask - simple task exec
09:11:13.535 [main] DEBUG com.carl.callback.Main - st executer
https://github.com/iluwatar/java-design-patterns
之前的印象是回调有点像递归调用,但是用 java 写出来这个回调,还是有点怪怪的感觉