JavaScript – Dependency Locator Pattern

GitHub Code

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.

Screen Shot 2017-03-19 at 5.27.28 PM

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).

Screen Shot 2017-03-19 at 5.33.13 PM

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.

Screen Shot 2017-03-19 at 5.30.38 PM

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.

Screen Shot 2017-03-19 at 5.31.43 PM

‘DependancyLocatorImpl’ implements the ‘IDependancyLocator’ interface.  It defines a common set of activities and dependancy has to implement to be used by the system.

Screen Shot 2017-03-19 at 5.35.39 PM

To run:

  • Download code, run and post

Screen Shot 2017-03-19 at 5.24.36 PM

  • Review results

Screen Shot 2017-03-19 at 5.24.15 PM

Stay tuned!






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s