Service Locator

Service locator is quite similar to the singleton pattern, as it can be used to provide global access. The main difference is, that with service locator we are not going to try to control the life cycles of the services. The pattern has only a single responsibility, to locate a service and return it to the client. For this task, we will have a look at two different implementations of this pattern. 

 

Part 1: A reliable service locator

Implement a service locator reliable service locator. For this, we will presume, that there is a need for services named PlayerProfile, MapFactory and ObjectPool. As we do not have implementations of these services you should provide null services instead. See Game Programming Patterns for the description of a null service.

Requirements checklist

  • The services are provided using dependency injection. I.e another class initializes the services using the Provide method.
  • Possible to register classes of interfaces IProfile, IMapFactory, IObjectPool
  • Access services using properties or getter methods. 
  • If a service isn't provided a NullObject is returned. Eg instead of actual profile, an object of type NullProfile is returned.

 

Part 2: A script registry

Create a service locator, which can provide access to any class. While this implementation is very powerful, it also has a major downside. Using this approach it is up to the client classes to check for null references. 

Requirements checklist

  • A single instance of any class can be registered to the locator. 
  • Classes can be registered to the locator using a static Provide method. 
  • Locate objects using a GetScript method similar to the GetComponent available in Unity. Use of generics is recommended, but not necessary.
  • If an instance of the requested class isn't available, then return a null.

 

;