考虑到设计模式,我想知道在方法参数中定义操作的回调是否比在对象中定义回调并通过 setter 进行设置更糟糕。
我不确定是否存在有关回调创建的设计模式。
例如,假设有某个类 A,我想执行带有回调的 methodM。
public class A {
public interface Callback {
void onEvent();
}
public static methodM(...) {
// ...
}
}
我可以这样做吗:
public static void methodM(Callback c) {
c.onEvent();
}
// ...
A.method(this); // The class that calls the method is the callback!
而不是:
public static void setCallback(Callback callback) {
this.callback = callback;
}
public static void methodM() {
this.callback.onEvent();
}
// ...
A.setCallback(this); // The class that calls the method is the callback!
A.method();
请注意,该方法是静态的事实只是为了便于场景理解。
那么,我可以使用第一种方法作为有效的设计吗?
使用第一个场景的原因是为了避免内存泄漏,以便轻松定义多个执行的简单回调,因为我必须使用列表、观察者等来控制回调列表。
最佳答案
我不认为有“回调模式”,它太通用了。
然而,许多设计模式都使用回调,例如 Observer pattern或Visitor pattern
这取决于您程序的全局架构
那段代码
public static void methodM(Callback c) {
c.onEvent();
}
// ...
A.method(this); // The class that calls the method is the callback!
不会打扰我,如果这样呈现,这并不是禁止的事情
关于java - 设计模式: Callback as a method parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26607044/