Search code examples
javaapache-commonsevent-listener

Event listener in java


We desing our application with base classes and Event Listener approch, thus the base class and a event listener interface. base class invoke appropriate event listener method after call any operation. Following code shows my design :

import java.util.EventListener;

public interface MyEventListener extends EventListener
{
    public void preOperation();

    public void postOperation();
}

Then I implement this interface as following :

class MyEventListenerImpl implements MyEventListener
{
    @Override
    public void postOperation()
    {
        System.out.println("Do previous operation");
    }

    @Override
    public void preOperation()
    {
        System.out.println("Do post operation");
    }
}

Then I write base class as following :

abstract class Base
{
    private MyEventListener eventListener; /* this member injected */

    public abstract void operation_1();

    public void doOperation_1()
    {
        eventListener.preOperation(); /* call listener before invoking main operation_1 implementation */

        operation_1(); /* call main operation_1 implementation */

        eventListener.postOperation(); /* call listener after invoking main operation_1 implementation */
    }
}

after these works I write my implementation of Base class and implement operation_1 method. I do this approach by java.util.EventListener marker interface but after design my problem see another class :

  1. Abstract class EventListenerProxy in java.util package.
  2. EventListenerSupport generic class in org.apache.commons.lang3.event package.

I don't know using these class never. I want know two things:

  1. Your opinions about my design.(good or bad)
  2. best practice for Event Listener approach.(by said class or any third party frameworks)

Solution

  • It's hard to discuss about a particular design without knowing which problem it's supposed to solve.

    Anyway, the principal problem with your design is that you can only have one listener. Using EventListenerSupport would allow easily supporting several ones, and would make the add/remove listener methods trivial to implement.

    Another problem is that your listener methods don't take any event as parameter. This makes it impossible for a single listener to listen to several Base instances, because it can't use the event to detect the source of the event.