I decided to explore this pattern because I heard it referred to at work in relation to Dependency Injection (DI). It caught my attention because I wasn’t expecting to hear ‘service locator pattern’ in relation to DI. My first thought was ‘what does locating a service have to do with DI’?
After reading up on the pattern, it made sense to me. In essence, it is my understanding that the ‘locator’ is an abstraction for getting access to dependancies. So, I have labeled this version ‘the dependancy locator’ pattern because I believe this is more accurate. Whether it is a service, a database client or something else, they are dependancies that need to be made available to some consumer of that dependancy.
Following this model (see reference #1), I created a sample that returns a customer repository, a data service and an HTTP client.
Each dependancy is created from the abstract class ‘DependancyAbstract’. In this sample, this class only defines a name. Normally, there would have to be more benefit to creating an abstract class then just a name. But, I wanted to show that in a real implementation, an abstract or base class would most likely be created (in my opinion).
This sample is run via the driver module ‘dependancyLocatorDriver.js’. This module is an facade for what would normally be a complex set of classes/files/etc that use the dependancies.
The main actor in the driver is ‘DependencyLocatorImpl’. It is the locator implementation that handles all of the connection and implementation details for any dependencies that subscribing systems need. Each dependency is stored in the locator class which has basic dependency management methods for register, get and delete.
‘DependancyLocatorImpl’ implements the ‘IDependancyLocator’ interface. It defines a common set of activities and dependancy has to implement to be used by the system.
- Download code, run and post
- Review results