Skip to content
Advertisement

Avoid Service locator in strategy design pattern [closed]

Take a look on that pseudocode

JavaScript

As service locator is considered as anti pattern, how to avoid it in this case? A,B,C can have various dependencies, thats why I would like to instantiate it using all benefits of dependency injections. I could albo inject A,B,C as dependencies of StrategyResolver, but what if I have there like 10 strategies. The StrategyResolver dependency list is then too long.

Advertisement

Answer

If you are using Spring you can inject all known beans of a certain type automatically:

JavaScript

If this is the only constructor Spring will have no trouble injecting all the beans implementing the StrategyInterface. Of course those beans need to be known to Spring using for example the @Named annotation on the class:

JavaScript

BTW why not just name the interface ‘Strategy’? The ‘Interface’ suffix does not really add anything.

EDIT: to determine which Strategy applies you can add a method to the Strategy interface:

JavaScript

In the StrategyResolver you would have code like this:

JavaScript

Or in more recent style:

JavaScript

One gotcha here is that to avoid the exception above you must ensure that a strategy always applies. You could create a ‘DefaultStrategy’ which always applies and is added as the last strategy in the list, e.g:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement