views:

176

answers:

3

I am looking for a way to do the following:

A Project : Defines an abstract class that is called when some events happen (event handler if you will) Defines the engine that will fire the events using the event handler above

B Project: Defines the implementation for the abstract class Runs the engine.

How can i register the implementation class and make sure that is the one being called when the engine runs.

EDIT 1: By register i mean i must somehow define which is the implementation that should be called for that given abstract object

Sorry if the question isn't too clear, let me know if you need some more details

+2  A: 

Something like this?

class A implements EventHandlerForB {
...
}

public class B {
  private EventHandlerForB eventHandler;

  public void registerEventHandler(EventHandlerForB eventHandler) {
    this.eventHandler = eventHandler;
  }
...
}

public interface EventHandlerForB {
...
}
palindrom
Passing it thought the constructor is probably better for unicast.
Tom Hawtin - tackline
This solution did require me to code the class that invokes the handler, which i am not doing. using your objects, in my problem class B would be closed and class A would be what i implement.
Nuno Furtado
A: 

there are several "patterns" that try to address this issue. Using only JDK (6 or above) classes you may want to take a look at java.util.ServiceLoader

dfa
Nooooooooooo!!!!!!!!!! Not ServiceLoader!
Tom Hawtin - tackline
why not? please explain!
dfa
+1  A: 

At runtime, you can have the name of the implementation passed in your A project (with a properties file or a Java system property). Then you find this class in the classpath with class.forName() and instantiate it with newInstance().

But you'd prefer using a framework like Guice or Spring, that will allow you to glue stuff together in a clean way.

fg
+1 for the guice link
Nuno Furtado
The solution i implemented is based on your first sugestion, i had a look at Guice and may end up going for it, but for now this is enough thx
Nuno Furtado