Define Implementation for abstract Object

2019-07-27 03:47发布

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

3条回答
趁早两清
2楼-- · 2019-07-27 03:58

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-27 03:59

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.

查看更多
Explosion°爆炸
4楼-- · 2019-07-27 04:22

Something like this?

class A implements EventHandlerForB {
...
}

public class B {
  private EventHandlerForB eventHandler;

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

public interface EventHandlerForB {
...
}
查看更多
登录 后发表回答