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?
The main difference is how the dependencies are located, in Service Locator, client code request the dependencies, in DI Container we use a container to create all of objects and it injects dependency as constructor parameters (or properties). Dependency Injection doesn't require the use of a DI Container though.
Service Locator is a dangerous pattern because it almost works. You can locate Dependencies from consuming classes, and you can replace those Dependencies with different implementations — even with Test Doubles from unit tests.
Java. The main difference between a “factory method” and an “abstract factory” is that the factory method is a single method, and an abstract factory is an object. The factory method is just a method, it can be overridden in a subclass, whereas the abstract factory is an object that has multiple factory methods on it.
The Abstract Factory design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With