开发者

Are there any general listeners defined in Android or Java

Sometimes I want a simple generic Listener without defining my own class. Is there a predefined "something开发者_如何学Python happened and here is a string or object or whatever" in Java or Android?


A project I've worked on had that. It lead to some frightfully unreadable and unmaintainable code once a class implemented the "MyListener" interface to handle two completely different kind of events. There was a lack of separation of concerns, and you had no idea when or how that method might be invoked.

public interface GenericListener {
    public void handleMyEvent(Object sourceObj, int eventCode);
}

//...later on there's some implementation
public void handleMyEvent(Object sourceObj, int eventCode) {
    if ( sourceObj == startDownloadButton && eventCode == MyButton.CLICKED ) {
        //... 20 lines of code to start download
    } else if ( sourceObj instanceOf DownloadStatus && eventCode == DownloadStatus.COMPLETE ) {
        //... 10 lines of code to display status
    } else //... and on and on...
}

This isn't the kind of code duplication you need to avoid. Just because two methods/interfaces share the same basic signature doesn't mean they should be combined into one. I suggest you create listener interfaces that are completely self-documenting with regards to when and how they are used.


There's java.util.Observer, but that only works for Observable subclasses. (That is, anything can implement the Observer interface, but it can only observe Observable objects.)


If you want to avoid defining a listener class, consider defining callback methods directly in the observable:

abstract class MyWorker{

    public MyWorker(){
        //...    
        onComplete(); 
    }

    protected abstract void onComplete();

}

Then override them later:

new MyWorker(){

    protected void onComplete(){
        //..
    }
}

Obviously, this is not suitable for every situation. Sometimes you need a real listener class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜