How to create custom Listeners in java?

北战南征 提交于 2019-12-02 18:01:59

Have a look at the source of any class that uses listeners. In fact it's quite easy:

  • create an interface for your listener, e.g. MyListener
  • maintain a list of MyListener
  • upon each event that the listeners should listen to, iterate over the list and call the appropriate method with some event parameter(s)

As for the observer pattern along with some Java code have a look at wikipedia.

do01

https://stackoverflow.com/a/6270150/3675925

You probably want to look into the observer pattern.

Here's some sample code to get you started:

import java.util.*;

// An interface to be implemented by everyone interested in "Hello" events
interface HelloListener {
    void someoneSaidHello();
}

// Someone who says "Hello"
class Initiater {
    private List<HelloListener> listeners = new ArrayList<HelloListener>();

    public void addListener(HelloListener toAdd) {
        listeners.add(toAdd);
    }

    public void sayHello() {
        System.out.println("Hello!!");

        // Notify everybody that may be interested.
        for (HelloListener hl : listeners)
            hl.someoneSaidHello();
    }
}

// Someone interested in "Hello" events
class Responder implements HelloListener {
    @Override
    public void someoneSaidHello() {
        System.out.println("Hello there...");
    }
}

 

class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();

        initiater.addListener(responder);

        initiater.sayHello();  // Prints "Hello!!!" and "Hello there..."
    }
}

There is no built-in mechanism that would allow you to attach listeners to all variables. The object you want to watch needs to provide the support for that by itself. For example it could become Observable and fire off onChange events to its Observers (which you also have to ensure are being tracked).

I would recommend using EventBus for your use case. It has a nice API design and is easy to use. Have a look at their Getting Started section to see how it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!