Is the Service Locator pattern any different from the Abstract Factory pattern?

Merlyn Morgan-Graham picture Merlyn Morgan-Graham · Apr 18, 2011 · Viewed 11.1k times · Source

At first glance, the Service Locator pattern looks the same as the Abstract Factory pattern to me. They both seem to have the same use (you query them to receive instances of abstract services), and they both have been mentioned when I read about Dependency Injection.

However, I have seen the Service Locator pattern described as a poor idea, but have seen direct support for the Abstract Factory pattern in at least one major Dependency Injection framework.

If they aren't the same, what are the differences?

Answer

Gyan aka Gary Buyn picture Gyan aka Gary Buyn · Feb 22, 2012

I have stumbled across the same question while investigating these patterns. I think the major differences can be found between a Service Locator and a Factory (whether it is abstract or not):

Service Locator

  • 'Locates' an existing dependency (the service). Although the service may be created during resolution, it is of no consequence to the Client because:
  • The Client of the Service Locator does NOT take ownership of the dependency.

Factory

  • Creates a new instance of a dependency.
  • The Client of the Factory takes ownership of the dependency.

Abstract Factory

  • Same as a regular Factory except that different deployments may use different implementations of the Abstract Factory allowing different types to be instantiated in those different deployments (you could even change the implementation of the Abstract Factory at runtime but that's not usually how it's used.)