Junior — Middle
Explain the principle of the service locator pattern and its main features.
sobes.tech AI
Answer from AI
The Service Locator pattern is a way of organizing access to dependencies and services in an application through a centralized object (the locator). Instead of explicitly passing dependencies, components request the necessary services from the service locator.
Main features:
- Centralized management of dependencies.
- Simplifies component code, as they do not know how services are created.
- Ability to replace service implementations in one place.
However, the pattern is criticized for hiding dependencies, which complicates testing and understanding the code, as dependencies are implicit.
Example of usage:
class ServiceLocator {
constructor() {
this.services = new Map();
}
register(name, instance) {
this.services.set(name, instance);
}
get(name) {
return this.services.get(name);
}
}
const locator = new ServiceLocator();
locator.register('logger', console);
const logger = locator.get('logger');
logger.log('Message');
In tests, services can be replaced with mocks by registering them in the locator.