Knowing about the Service Locator pattern

Injection isn't the only way to loosen the components/service dependencies. Another way is to use the service locator.

Basically, a service locator is a sort of a registry object (a factory) that knows how to create the services or components that an application might need. For obvious reasons, this primarily shifts the burden of object creation from an individual class to the factory and we still have to get the locator object inside the classes using it, which results in the dependency of the locator itself.

We can also have more than one type of service locator inside an application. For example, FakeServiceLocator, whose purpose is just to provide the fakes that can be tested in the testing framework.

Your service locator can internally use the abstract factory pattern or the builder pattern, as appropriate. It can also be a static or dynamic service locator, where in the dynamic service locator, it may keep the object with string keys, for example, by maintaining the objects in Hashmaps.

A simple code for the dynamic service locator implemented as a singleton factory catalog would be as follows inside OrderProcessor:

    IOrderRepository repository = (IOrderRepository) 
serviceLocator.Instance.getService("OrderRepository");
More conceptual information on dependency resolutions
There are discussions separately on service locator that it does not completely follows SOLID design principles and good OO practices, but we leave that discussion out of this book.
For more information on dependency resolution, refer to Inversion of Control Containers and the Dependency Injection pattern on Martin Fowler's website https://martinfowler.com/articles/injection.html.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57