Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/5698026/is-the-service-locator-pattern-any-different-from-the-abstract-factory-pattern

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...