Define Implementation for abstract Object

2019-07-27 03:27发布

问题:

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

回答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.



回答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 {
...
}


回答3:

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