HomeToolsAbout

Service Locator

What is it

ServiceLocator is a singleton Registry.

Dependency Injection and Service Locator both performs wiring of application.

Problem with service locator pattern

service locator makes a class expect a locator, not which service is actually needed.

Will be easy to end up in errors like KeyNotFoundException.

For this reason, prefer constructor injection pattern over service locator pattern.

class MovieLister... MovieFinder finder = ServiceLocator.movieFinder(); class ServiceLocator... public static MovieFinder movieFinder() { return soleInstance.movieFinder; } private static ServiceLocator soleInstance; private MovieFinder movieFinder; class Tester... private void configure() { ServiceLocator.load(new ServiceLocator(new ColonMovieFinder("movies1.txt"))); } class ServiceLocator... public static void load(ServiceLocator arg) { soleInstance = arg; } public ServiceLocator(MovieFinder movieFinder) { this.movieFinder = movieFinder; } // test class Tester... public void testSimple() { configure(); MovieLister lister = new MovieLister(); Movie[] movies = lister.moviesDirectedBy("Sergio Leone"); assertEquals("Once Upon a Time in the West", movies[0].getTitle()); }
AboutContact