2011-01-21 13 views
3

我想設計一個Java系統是simliar到C#代表的概念。的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中完成它。

有沒有人有這樣一個工作examle,我可以看到?

感謝
斯蒂芬妮

回答

13

在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來管理它。

是的,這是瘋狂繁瑣。你的眼睛不會騙你。