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 (2)

User avatar

Than you for this example. It works perfectly!

by MrJW |  Reply
User avatar

Good! Simple and clear!

by wibrst |  Reply

Add comment