Junior — Middle
How does using the Service Locator pattern differ from dependency injection in application design?
sobes.tech AI
Answer from AI
The Service Locator pattern and Dependency Injection (DI) are two approaches for managing dependencies in an application, but they differ in how they organize and control dependencies.
Service Locator:
- Represents an object (locator) that knows how to create and provide the necessary services.
- Application components request dependencies from the locator at runtime.
- Components depend on the locator, creating a hidden dependency.
- Convenient for quick access to services but complicates testing and reduces transparency of dependencies.
Dependency Injection:
- Dependencies are passed to components from outside (e.g., through constructor, setter, or interface).
- Components explicitly declare their dependencies.
- Improves modularity and testability, as dependencies can be easily replaced.
- Requires more explicit management of object creation, often with frameworks or containers.
Example:
# Service Locator
class ServiceLocator:
services = {}
@classmethod
def add_service(cls, name, service):
cls.services[name] = service
@classmethod
def get_service(cls, name):
return cls.services.get(name)
class UserService:
def get_user(self):
return "User"
# Usage
ServiceLocator.add_service('user', UserService())
class Controller:
def __init__(self):
self.user_service = ServiceLocator.get_service('user')
def show_user(self):
print(self.user_service.get_user())
# Dependency Injection
class ControllerDI:
def __init__(self, user_service):
self.user_service = user_service
def show_user(self):
print(self.user_service.get_user())
user_service = UserService()
controller = ControllerDI(user_service)
In conclusion, DI is considered more suitable for maintainable and testable code, while Service Locator may be simpler in small projects but leads to less transparent architecture.