To decouple the code, you can have a service locator, but it's not the same as global variables / state ?.
I know that these often end with interfaces, so you go through the interface and get a specific class, but still my question is.
For example:
class Something {
void DoSomething() {
IMyType myType = ServiceLocator.GetSerivceTypeOf(IMyType);
}
}
Here, the class requires MyType, which is created somewhere else, but instead of passing MyType down through chains (through constructors, etc.), it is obtained in this way.
I asked this question at an early stage of my professional career as a developer - before that I had not come across this model. Anthony nailed my opinion (and, therefore, now the selected answer) on the service locator - in fact, I consider them as anti-patterns, like others. The links provided are a good starting point - but to answer my own question after all this time, they act like a global state and should be avoided. Prefer a standard dependency injection;)
source
share