This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages)
|

The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the "service locator", which on request returns the information necessary to perform a certain task. Proponents of the pattern say the approach simplifies component-based applications where all dependencies are cleanly listed at the beginning of the whole application design, consequently making traditional dependency injection a more complex way of connecting objects. Critics of the pattern argue that it is an anti-pattern which obscures dependencies and makes software harder to test.[better source needed]
IShippingStrategy instance obtained via a service location call, supplying a ShippingContext as a parameter to service locator stating what is being shipped from where and where to, so service locator can match the best case (e.g. using a pattern match score). This significantly simplifies complex business application architecture (e.g. medical scoring systems, routing) where circuitous decision making can be done via scoring of the best matching strategy located dynamically at a runtimeConsider a simple logging framework:
interface Logger {
void log(String message);
}
class ConsoleLogger implements Logger {
public void log(String message) {
System.out.println("LOG: " + message);
}
}
A service locator for such a system would be the following:
class LoggerServiceLocator {
private static Logger logger = new ConsoleLogger();
// Obtain the logger
public static Logger getLogger() {
return logger;
}
// Allow replacing a logger
public static void registerLogger(Logger replacement) {
logger = replacement;
}
}
This allows the client application to not have to instantiate the logger directly, but rather obtain it through the provider:
Logger logger = LoggerServiceLocator.getLogger();
logger.log("Obtained logger from LoggerServiceLocator.");