Java 中的通用回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15260596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:01:32  来源:igfitidea点击:

Generic callback in Java

javagenericscallback

提问by PNS

What should be the preferable Javainterface or similar pattern that could be used as a generic callback mechanism?

Java可以用作通用回调机制的首选接口或类似模式应该是什么?

For example it could be something like

例如它可能是这样的

public interface GenericCallback
{
    public String getID();
    public void callback(Object notification);
    // or public void callback(String id, Object notification);
}

The ID would be needed for cases of overriden hashCode()methods so that the callee identifies the caller.

对于覆盖hashCode()方法的情况,将需要 ID,以便被调用者识别调用者。

A pattern like the above is useful for objects that needs to report back to the class they were spawned from a condition (e.g., end of processing).

像上面这样的模式对于需要向它们从条件(例如,处理结束)产生的类报告回的对象很有用。

In this scenario, the "parent" class would use the getID()method of each of these GenericCallbackobjects to keep a track of them in a Map<String, GenericCallable>and add or remove them according to the notification received.

在这种情况下,“父”类将使用getID()这些GenericCallback对象中的每一个的方法来跟踪它们,Map<String, GenericCallable>并根据收到的通知添加或删除它们。

Also, how should such an interface be actually named?

另外,这样的接口实际上应该如何命名?

Many people seem to prefer the Java Observer pattern, but the Observable classdefined there is not convenient, since it not an interface to circumvent single inheritance and it carries more functionality than actually needed in the above, simple scenario.

很多人似乎更喜欢Java Observer 模式,但是在那里定义的Observable 类并不方便,因为它不是绕过单一继承的接口,并且它承载了比上述简单场景中实际需要的更多功能。

回答by user949300

I would genericize the callback, based upon the type of Object passed. This is particularly useful for EventListeners listening for different classes of events. e.g.

我会根据传递的对象类型对回调进行泛化。这对于侦听不同类事件的 EventListeners 尤其有用。例如

public interface Callback<T> {
   public void callback(T t);
}

You maybe able to use the type T as the key in a Map. Of course, if you want to differentiate between two callbacks that take the same argument, like a String, then you'd need something like your getID().

可以使用类型 T 作为 Map 中的键。当然,如果您想区分采用相同参数的两个回调,例如字符串,那么您需要像getID().

Here my old blog about using this for Event ListenersThe interface Events.Listenercorresponds to Callback<T>above. And Broadcastersuses a Map to keep track of multiple listeners based upon the class they accept as the argument.

这是我关于将其用于事件侦听器旧博客接口Events.Listener对应于Callback<T>上面。和广播使用地图来追踪基于他们接受作为参数的类多听众。

回答by Jeff

I'd recommend using Observer patternsince the Observer pattern is the gold standard in decoupling - the separation of objects that depend on each other.

我建议使用观察者模式,因为观察者模式是解耦的黄金标准——分离相互依赖的对象。

But I'd recommend avoiding using the Java.util.Observable classif you are looking for a generic callback mechanism. Because Observable has a couple of weaknesses: it's not an interface, and forces you to use Object to represent events.

但如果您正在寻找通用回调机制,我建议避免使用Java.util.Observable 类。因为 Observable 有两个弱点:它不是一个接口,并且强制您使用 Object 来表示事件。

You can define your own event listener like this:

您可以像这样定义自己的事件侦听器:

public class MyEvent extends EventObject {
    public MyEvent(Object source) {
        super(source);
    }
}

public interface MyEventListener {
    void handleEvent(EventObject event);
}

public class MyEventSource {
    private final List<MyEventListener> listeners;
    public MyEventSource() {
        listeners = new CopyOnWriteArrayList<MyEventListener>();
    }
    public void addMyEventListener(MyEventListener listener) {
        listeners.add(listener);
    }
    public void removeMyEventListener(MyEventListener listener) {
        listeners.remove(listener);
    }
    void fireEvent() {
        MyEvent event = new MyEvent(this);
        for (MyEventListener listener : listeners) {
            listener.handleEvent(event);
        }
    }
}

回答by lemil77

looks like you want to implement the Observer pattern. In this urlis a complete implementation for the observer pattern in Java. In your case the observer will be the callback.

看起来你想实现观察者模式。在这个网址是在Java中的观察者模式的完整实现。在您的情况下,观察者将是回调。

Also If you need to implement something more complex, you will end up doing an event/notifier pattern. Take a look at this other pattern here.

此外,如果您需要实现更复杂的东西,您最终将使用事件/通知程序模式。看看这个其他方式在这里

Thanks, @leo.

谢谢,@leo。