IoC 在运行时决定具体实现
IoC Deciding specific implemetation at runtime
我想在我的框架中实现一些控制反转。
所以我有一个接口 GenericDatabase
定义了必须实现的方法。我事先不知道哪个 类 会实现这个,但我有调用接口方法的方法。因此,在运行时,我需要从配置文件中读取应该使用哪个特定实现(否则,我将不得不知道用户可能使用的所有潜在实现 类)。我已经阅读了一些 Martin Fowler 的文章,但没有弄清楚这个问题。
我怎样才能做到这一点?
我想我正在尝试类似的东西:
GenericDatabase database = Class.forName("com.example.myCustomDatabase").newInstance();
还有一个障碍,它应该在 try-with-resources 中:
try (GenericDatabase database = Class.forName("com.example.myCustomDatabase").newInstance()) {
经过一些测试,我可能是错的,我认为正确的方法是:
try (GenericDatabase database = (GenericDatabase) Class.forName("com.example.myCustomDatabase").newInstance()) {
与:
public interface GenericDatabase extends AutoCloseable {
其中 com.example.myCustomDatabase
从配置文件中读取。
我想在我的框架中实现一些控制反转。
所以我有一个接口 GenericDatabase
定义了必须实现的方法。我事先不知道哪个 类 会实现这个,但我有调用接口方法的方法。因此,在运行时,我需要从配置文件中读取应该使用哪个特定实现(否则,我将不得不知道用户可能使用的所有潜在实现 类)。我已经阅读了一些 Martin Fowler 的文章,但没有弄清楚这个问题。
我怎样才能做到这一点?
我想我正在尝试类似的东西:
GenericDatabase database = Class.forName("com.example.myCustomDatabase").newInstance();
还有一个障碍,它应该在 try-with-resources 中:
try (GenericDatabase database = Class.forName("com.example.myCustomDatabase").newInstance()) {
经过一些测试,我可能是错的,我认为正确的方法是:
try (GenericDatabase database = (GenericDatabase) Class.forName("com.example.myCustomDatabase").newInstance()) {
与:
public interface GenericDatabase extends AutoCloseable {
其中 com.example.myCustomDatabase
从配置文件中读取。