gpt4 book ai didi

java - 包装类不适合回调框架

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:27 26 4
gpt4 key购买 nike

The disadvantages of wrapper classes are few. One caveat is that wrapper classes are not suited for use in callback frameworks, wherein objects pass self references to other objects for subsequent invocations (“callbacks”). Because a wrapped object doesn’t know of its wrapper, it passes a reference to itself (this) and callbacks elude the wrapper.

有人可以举例说明这意味着什么吗?它是用 Effective Java 编写的,但我没有完全理解它。

为了增加上下文,我们应该支持组合而不是继承,这会导致子类 Set 我们应该使用这样的东西:

public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) { this.s = s; }
public void clear() { s.clear(); }
public boolean contains(Object o) { return s.contains(o); }
...
}

但是,这将如何失败,我仍然无法理解回调。在 JavaScript 中,我们可以使用函数回调,但如果有人可以解释的话,同样的概念如何适用于 Java。

最佳答案

如果你能保证你总是在任何地方(为了将来的回调)传递一个被转发的对象的引用,那么一切都很好。尽管如此,您还是可以创建一个对象,用某个类包装它,但该对象本身可以有一些方法将 this 传递到某处,例如传递给某个监听器或其他地方。在这种情况下,您的包装器不知道包装对象发生了什么。例如:

// basic class which we will wrap
public class Model{
Controller controller;

Model(Controller controller){
this.controller = controller;
controller.register(this); //Pass SELF reference
}

public void makeChange(){
...
}
}

public class Controller{
private final Model model;

public void register(Model model){
this.model = model;
}

// Here the wrapper just fails to count changes,
// because it does not know about the wrapped object
// references leaked
public void doChanges(){
model.makeChange();
}
}

// wrapper class
public class ModelChangesCounter{
private final Model;
private int changesMade;

ModelWrapper(Model model){
this.model = model;
}

// The wrapper is intended to count changes,
// but those changes which are invoked from
// Controller are just skipped
public void makeChange(){
model.makeChange();
changesMade++;
}
}

Model 的包装器只是避开了来自 Controller 回调的 makeChange() 方法的调用。

关于java - 包装类不适合回调框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28254116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com