Wit*_*eso 4 java events listeners event-handling
我正在尝试设计一个与c#delegates概念相似的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)
{
}
}
Run Code Online (Sandbox Code Playgroud)
我通读了这个网站:http://www.javaworld.com/javaqa/2000-08/01-qa-0804-events.html?page = 1
他们参考手动实现整个"订阅列表".但是代码不是一个完整的例子,而且我已经习惯了c#,因为我无法理解如何在java中完成它.
有没有人能够看到我能看到的工作考试?
谢谢
斯蒂芬妮
900*_*000 16
在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
Run Code Online (Sandbox Code Playgroud)
通常,您可以通过匿名类创建简单的侦听器:
someProducer.setEventListener(new ProducerEventListener(){
public void onFooHappened(FooEvent e) {
log.info("Got " + e.getAmount() + " of foo");
}
public void onBarOccured(BarEvent e) {} // ignore
});
Run Code Online (Sandbox Code Playgroud)
如果您希望每个事件允许许多侦听器(例如GUI组件),您可以管理一个通常要同步的列表,并拥有addWhateverListener并removeWhateverListener管理它.
是的,这是疯狂的繁琐.你的眼睛不骗你.
| 归档时间: |
|
| 查看次数: |
10314 次 |
| 最近记录: |