我正在尝试设计一个类似于 c# 委托(delegate)概念的 Java 系统。
这是我希望实现的基本功能:
public class mainform
{
public delegate onProcessCompleted
//......
processInformation()
{
onProcessCompleted(this);
}
//......
}
//PLUGIN
public class PluginA
{
public PluginA()
{
//somehow subscribe to mainforms onProcessingCompleted with callback myCallback()
}
public void myCallback(object sender)
{
}
}
我已经阅读了这个网站:http://www.javaworld.com/javaqa/2000-08/01-qa-0804-events.html?page=1
他们提到手动实现整个“订阅列表”。但是代码不是一个完整的示例,而且我已经习惯了 c#,以至于我无法理解如何在 java 中完成它。
有没有人有我能看到的这方面的工作考试?
谢谢
斯蒂芬妮
最佳答案
在 Java 中,您没有函数委托(delegate)(有效的方法引用);您必须传递实现某个接口(interface)的整个类。例如
class Producer {
// allow a third party to plug in a listener
ProducerEventListener my_listener;
public void setEventListener(ProducerEventListener a_listener) {
my_listener = a_listener;
}
public void foo() {
...
// an event happened; notify the listener
if (my_listener != null) my_listener.onFooHappened(new FooEvent(...));
...
}
}
// Define events that listener should be able to react to
public interface ProducerEventListener {
void onFooHappened(FooEvent e);
void onBarOccured(BarEvent e);
// .. as many as logically needed; often only one
}
// Some silly listener reacting to events
class Consumer implements ProducerEventListener {
public void onFooHappened(FooEvent e) {
log.info("Got " + e.getAmount() + " of foo");
}
...
}
...
someProducer.setEventListener(new Consumer()); // attach an instance of listener
通常您有通过适当的匿名类创建的简单监听器:
someProducer.setEventListener(new ProducerEventListener(){
public void onFooHappened(FooEvent e) {
log.info("Got " + e.getAmount() + " of foo");
}
public void onBarOccured(BarEvent e) {} // ignore
});
如果您希望每个事件允许多个监听器(例如 GUI 组件),您可以管理一个您通常希望同步的列表,并具有 addWhateverListener
和 removeWhateverListener
对其进行管理。
是的,这非常麻烦。你的眼睛不会骗你。
关于用于订阅的 Java 监听器设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4763225/