用于订阅的Java侦听器设计模式

我正在尝试设计一个与c#delegates概念相似的Java系统。

这是我希望实现的基本function:

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中,您没有函数委托(有效的方法引用); 你必须传递一个实现某个接口的整个类。 例如

 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组件),您可以管理通常希望同步的列表,并使用addWhateverListenerremoveWhateverListener来管理它。

是的,这非常麻烦。 你的眼睛不骗你。