1

我有一个正在构建的小型 Web 应用程序。主要是为了提高我的单元测试能力(并进一步解耦我的代码),我正在实现一个服务定位器模式来查找某些依赖项的具体实现。我对 Service Locator 单例类本身非常满意,但我很好奇将它放在哪里以及如何加载它。单例本质上管理接口的哈希图 -> 具体实现。

我的工作区中有几个项目:

1) 一个表示层项目,其中包含 servlet 代码和表示层处理。(使用下面的 2 和 3)

2)一个数据访问层项目,其中包含访问数据库等的代码(使用下面的 3)

3) 一个包含两层使用的各种数据模型的通用项目。(没有其他项目参考)

由于服务定位器是为上述项目 1 和 2 中的类的实现提供服务,我想知道最好把它放在哪里?

我坚持的另一个问题是如何最好地使用默认实现加载它。一种选择是将所有默认实现放入单例服务定位器类的构造函数中。例如:

private ServiceLocator() {
   services.put(ISomeClass.class, new SomeClass());
   ....
}

另一种选择是拥有一个单独的类,其职责是使用默认实现加载 ServiceLocator。但接下来的问题是如何调用它,以便在任何其他类之前加载默认实现。

所以我想我的两个问题是:

1) ServiceLocator 最适合哪个项目?

2) 您推荐哪些解决方案来加载具有默认实现的类?

谢谢

4

1 回答 1

1

I think Martin Fowlers article on Dependency Injection addresses some of your questions. Personally I am not the biggest fan of the service locator pattern especially in Java where there are many high quality DI frameworks out there (although that it admittedly might be an overkill, but since you have to think about these kinds of architectural decision on implementing the service locator already you might eventually need to switch anyway). To your questions:

1) I would say in a separate project that has dependencies on 1) and 2) 2) From the mentioned article:

Dependency injection and a service locator aren't necessarily mutually exclusive concepts. A good example of using both together is the Avalon framework. Avalon uses a service locator, but uses injection to tell components where to find the locator.

So you could also use dependency injection to fill the locator with default implementations.

于 2011-06-09T15:33:04.820 回答