Java: Creating a custom event

Here’s an example of how create your own events and listen to them. It’s called the observer pattern. In this example the initiator prints “Hello” and the HelloListener responds with “Hello there!”.

// 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!");
    }
}

And here’s a little example runner:

class Test {
    public static void main(String[] args) {
        Initiater initiater = new Initiater();
        Responder responder = new Responder();
        initiater.addListener(responder);
        initiater.sayHello();  // "Hello!" and "Hello there!"
    }
}

Comments

Be the first to comment!