Files
java-design-patterns/service-locator
Ilkka Seppälä 6cd2d0353a docs: Content SEO updates (#2990)
* update yaml frontmatter format

* update abstract document

* update abstract factory

* use the new pattern template

* acyclic visitor seo

* adapter seo

* ambassador seo

* acl seo

* aaa seo

* async method invocation seo

* balking seo

* bridge seo

* builder seo

* business delegate and bytecode seo

* caching seo

* callback seo

* chain seo

* update headings

* circuit breaker seo

* client session + collecting parameter seo

* collection pipeline seo

* combinator SEO

* command seo

* cqrs seo

* commander seo

* component seo

* composite seo

* composite entity seo

* composite view seo

* context object seo

* converter seo

* crtp seo

* currying seo

* dao seo

* data bus seo

* data locality seo

* data mapper seo

* dto seo

* decorator seo

* delegation seo

* di seo

* dirty flag seo

* domain model seo

* double buffer seo

* double checked locking seo

* double dispatch seo

* dynamic proxy seo

* event aggregator seo

* event-based asynchronous seo

* eda seo

* event queue seo

* event sourcing seo

* execute around seo

* extension objects seo

* facade seo

* factory seo

* factory kit seo

* factory method seo

* fanout/fanin seo

* feature toggle seo

* filterer seo

* fluent interface seo

* flux seo

* flyweight seo

* front controller seo

* function composition seo

* game loop seo

* gateway seo

* guarded suspension seo

* half-sync/half-async seo

* health check seo

* hexagonal seo

* identity map seo

* intercepting filter seo

* interpreter seo

* iterator seo

* layers seo

* lazy loading seo

* leader election seo

* leader/followers seo

* lockable object seo

* rename and add seo for marker interface

* master-worker seo

* mediator seo

* memento seo

* metadata mapping seo

* microservice aggregator seo

* api gw seo

* microservices log aggregration seo

* mvc seo

* mvi seo

* mvp seo

* mvvm seo

* monad seo

* monitor seo

* monostate seo

* multiton seo

* mute idiom seo

* naked objects & notification seo

* null object seo

* object mother seo

* object pool seo

* observer seo

* optimistic locking seo

* page controller seo

* page object seo

* parameter object seo

* partial response seo

* pipeline seo

* poison pill seo

* presentation model seo

* private class data seo

* producer-consumer seo

* promise seo

* property seo

* prototype seo

* proxy seo

* queue-based load leveling seo

* reactor seo

* registry seo

* repository seo

* RAII seo

* retry seo

* role object seo

* saga seo

* separated interface seo

* serialized entity seo

* serialized lob seo

* servant seo

* server session seo

* service layer seo

* service locator seo

* service to worker seo

* sharding seo

* single table inheritance seo

* singleton seo

* spatial partition seo

* special case seo

* specification seo

* state seo

* step builder seo

* strangler seo

* strategy seo

* subclass sandbox seo

* table module seo

* template method seo

* throttling seo

* tolerant reader seo

* trampoline seo

* transaction script seo

* twin seo

* type object seo

* unit of work seo

* update method seo

* value object seo

* version number seo

* virtual proxy seo

* visitor seo

* seo enhancements

* seo improvements

* SEO enhancements

* SEO improvements

* SEO additions

* SEO improvements

* more SEO improvements

* rename hexagonal + SEO improvements

* SEO improvements

* more SEO stuff

* SEO improvements

* SEO optimizations

* SEO enhancements

* enchance SEO

* improve SEO

* SEO improvements

* update headers
2024-06-08 19:54:44 +03:00
..
2019-12-07 18:03:49 +02:00
2024-05-23 18:40:52 +03:00
2022-09-14 23:22:24 +05:30
2024-06-08 19:54:44 +03:00

title, shortTitle, description, category, language, tag
title shortTitle description category language tag
Service Locator Pattern in Java: Simplifying Service Access in Complex Systems Service Locator Master the Service Locator pattern in Java with our comprehensive guide. Learn how it simplifies dependency management in large-scale applications, promoting cleaner code and reusability. Structural en
Decoupling
Dependency management
Enterprise patterns
Instantiation

Also known as

  • Service Registry

Intent of Service Locator Design Pattern

The Java Service Locator pattern provides a method to decouple Java clients and services by using a central service registry.

Detailed Explanation of Service Locator Pattern with Real-World Examples

Real-world example

In a large hotel, the concierge desk acts as a Service Locator. When guests need a service, such as booking a restaurant reservation, finding transportation, or arranging a city tour, they do not directly seek out each service themselves. Instead, they go to the concierge desk, which locates and arranges the required services. This way, the guests are decoupled from the service providers and can rely on a central point to handle their requests, ensuring convenience and efficiency.

In plain words

The Service Locator pattern centralizes the logic for locating services, thereby decoupling clients from the concrete implementations of these services.

Wikipedia says

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 antipattern which obscures dependencies and makes software harder to test.

Programmatic Example of Service Locator Pattern in Java

The Service Locator design pattern is used to abstract the processes involved in obtaining a service. It uses a central registry, the "service locator", which returns the necessary information to perform a task upon request. This Java design pattern is particularly useful in enterprise Java applications where services need centralized management.

In this example, we have a Service interface and a ServiceLocator class. The Service interface defines the methods that all services must implement. The ServiceLocator class is responsible for retrieving and caching these services.

public interface Service {
    String getName();

    int getId();

    void execute();
}

The Service interface defines three methods: getName(), getId(), and execute(). Any class that implements this interface must provide an implementation for these methods.

public class App {

    public static final String JNDI_SERVICE_A = "jndi/serviceA";
    public static final String JNDI_SERVICE_B = "jndi/serviceB";

    public static void main(String[] args) {
        // Get the service from the ServiceLocator
        var service = ServiceLocator.getService(JNDI_SERVICE_A);
        // Execute the service
        service.execute();
        // Get another service from the ServiceLocator
        service = ServiceLocator.getService(JNDI_SERVICE_B);
        // Execute the service
        service.execute();
        // Get the service from the ServiceLocator again
        service = ServiceLocator.getService(JNDI_SERVICE_A);
        // Execute the service
        service.execute();
        // Get the service from the ServiceLocator again
        service = ServiceLocator.getService(JNDI_SERVICE_A);
        // Execute the service
        service.execute();
    }
}

In the App class, we use the ServiceLocator to get services by their names and then execute them. The ServiceLocator handles the details of looking up and caching the services. This way, the App class is decoupled from the concrete implementations of the services.

Here is the output from running the example:

15:39:51.417 [main] INFO com.iluwatar.servicelocator.InitContext -- Looking up service A and creating new service for A
15:39:51.419 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56
15:39:51.420 [main] INFO com.iluwatar.servicelocator.InitContext -- Looking up service B and creating new service for B
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceB is now executing with id 196
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceCache -- (cache call) Fetched service jndi/serviceA(56) from cache... !
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceCache -- (cache call) Fetched service jndi/serviceA(56) from cache... !
15:39:51.420 [main] INFO com.iluwatar.servicelocator.ServiceImpl -- Service jndi/serviceA is now executing with id 56

When to Use the Service Locator Pattern in Java

  • Use when you want to decouple service creation from client classes to reduce dependencies and improve code maintainability.
  • Applicable in large-scale enterprise applications where multiple services are used and dependencies need to be managed centrally.
  • Suitable when service instances need to be reused or shared among multiple clients.

Real-World Applications of Service Locator Pattern in Java

  • Enterprise Java applications often use Service Locator to manage business services.
  • Spring Framework uses a similar concept with its BeanFactory and ApplicationContext for dependency injection.
  • EJB (Enterprise JavaBeans) uses the Service Locator pattern to find and access EJB components.

Benefits and Trade-offs of Service Locator Pattern

Benefits:

  • Decouples client and service classes, reducing code dependencies.
  • Centralizes service management, making it easier to configure and manage services.
  • Promotes reuse of service instances, which can improve performance and resource utilization.

Trade-offs:

  • Can introduce a single point of failure if the Service Locator itself fails.
  • May add complexity to the codebase, especially in terms of configuration and maintenance.
  • Potential performance overhead due to the lookup mechanism.
  • Factory: Both patterns deal with object creation but Service Locator focuses on locating services while Factory focuses on creating them.
  • Dependency Injection: An alternative to Service Locator that injects dependencies directly into clients rather than having clients request them from a locator.
  • Singleton: Service Locator often uses Singleton pattern to ensure a single instance of the locator.

References and Credits