Pattern Recognition: Abstract Factory or Service Locator? by Mark Seemann
It's easy to confuse the Abstract Factory pattern with the Service Locator anti-pattern - particularly so when generics or contextual information is involved. However, it's really easy to distinguish between there two, and here's how!
Here are both (anti-)patterns in condensed form opposite each other:
|Abstract Factory||Service Locator|
public interface IFactory<T>
public interface IServiceLocator
For these examples I chose to demonstrate both as generic interfaces that take some kind of contextual information (context) as input.
In this example the context can be any object, but we could also have considered a more strongly typed context parameter. Other variations include more than one method parameter, or, in the degenerate case, no parameters at all.
Both interfaces have a simple Create method that returns the generic type T, so it's easy to confuse the two. However, even for generic types, it's easy to tell one from the other:
An Abstract Factory is a generic type, and the return type of the Create method is determined by the type of the factory itself. In other words, a constructed type can only return instances of a single type.
A Service Locator, on the other hand, is a non-generic interface with a generic method. The Create method of a single Service Locator can return instances of an infinite number of types.
An Abstract Factory is a generic type with a non-generic Create method; a Service Locator is a non-generic type with a generic Create method.
The name of the method, the number of parameters, and other circumstances may vary. The types may not be generic, or may be base classes instead of interfaces, but at the heart of it, the question is whether you can ask for an arbitrary type from the service, or only a single, static type.