Design Patterns (GoF) (50 Qs)•Part 3: Architectural Patterns & Enterprise Systems (25 - 35)
Service Locator Anti-Pattern vs Dependency Injection.
mid LevelMost AskedCode ExampleDependency Injection
In Simple Words:
- Service Locator: A central registry object that classes query to fetch dependencies:
typescript
class OrderService { process() { const db = ServiceLocator.get(Database); // Hidden dependency! } }- Why it's an Anti-Pattern: Hides dependencies from the class contract. Looking at the constructor, you have no idea what services the class requires until it crashes with a runtime
NullPointerException!
- Why it's an Anti-Pattern: Hides dependencies from the class contract. Looking at the constructor, you have no idea what services the class requires until it crashes with a runtime
- Dependency Injection: Dependencies are passed explicitly into the constructor (
new OrderService(database)), making all requirements visible and trivially mockable in tests.