Reputation: 6890
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 :
I don't know using these class never. I want know two things:
Upvotes: 0
Views: 3443
Reputation: 20703
An EventListener, by nature, can not know that something will happen, because it is triggered from inside operation_1
in your example.
What you are looking for are AOP method interceptors. Especially aopalliances MethodInterceptor interface will be useful to you:
public Operation1Interceptor implements MethodInterceptor {
Object invoke(MethodInvocation invocation) throws Throwable {
/* feel free to access the arguments, if you wish */
foo(invocation.getArguments())
Object retval = invocation.proceed();
/* Log it or do whatever you want */
bar(retval);
baz();
return retval;
}
}
The easiest way to use that is Google Guice, but there are some tutorials around.
Upvotes: 0
Reputation: 691715
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.
Upvotes: 1