开发者

Looking for help with implementation of Service Locator pattern

开发者 https://www.devze.com 2023-03-11 22:46 出处:网络
I have a small web application that I am building.Primarily to improve my unit testing ability (and also decouple my code further) I am implementing a service locator pattern to look up concrete imple

I have a small web application that I am building. Primarily to improve my unit testing ability (and also decouple my code further) I am implementing a service locator pattern to look up concrete implementations of some dependencies. I am mostly happy with the Service Locator singleton class itself, but I'm curious about where to put it and how to load it. The singleton essentially manages a hashmap of interface -> concrete implementations.

I have several projects in my workspace:

1) A presentation layer project which contains the servlet code and presentation layer processing. (uses 2 and 3 below)

2) A data access layer project which contains the code to access the databases etc. (uses 3 below)

3) A common project containing the various data models used by both layers. (no other project references)

Since the service locator is to serve up implementations of classes in both projects 1 and 2 above, I'm wondering where best to put it?

Another question I'm stuck on is how best to load it up with default implementations. One option is to put 开发者_Python百科all the default implementations into the constructor of the singleton service locator class. E.g.:

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

Another option is to have a separate class whose responsibility is to load the ServiceLocator with default implementations. But then the question is how to get it invoked so that the default implementations are loaded before any other class.

So I guess my two questions are:

1) In which project does the ServiceLocator best fit?

2) What solutions do you recommend for loading up the class with default implementations?

thanks


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消