1

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

Nuno Furtado
  • 4,548
  • 8
  • 37
  • 57
  • What do you mean by "register the implementation class"? – Thomas Owens Jul 27 '09 at 12:04
  • As far as I understand (maybe you can give some more clarification e.g. Pesudo Code) you would have to instantiate the actual B Project implementation as a reference to the A Project abstract class. – Daff Jul 27 '09 at 12:15

3 Answers3

2

Something like this?

class A implements EventHandlerForB {
...
}

public class B {
  private EventHandlerForB eventHandler;

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

public interface EventHandlerForB {
...
}
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
palindrom
  • 18,033
  • 1
  • 21
  • 37
1

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.
  • 331
  • 1
  • 3
  • 6
  • 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 Jul 28 '09 at 17:12
0

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
  • 114,442
  • 31
  • 189
  • 228