JavaOmnibus
J2EE Service Locator
J2EE pattern • Business
J2EEBusinessJava example

Service Locator solves a specific structural problem in the design.

Centralize service lookup and caching in one place.

Pattern overview

J2EE pattern

Centralize service lookup and caching in one place.

Intent

Provide a single access point that hides service-discovery mechanics and optionally caches results.

Problem

Many callers need the same infrastructure lookup logic and caching behavior.

Solution

Centralize lookup behind a locator rather than repeating discovery code everywhere.

Fit and tradeoffs

FamilyJ2EE
CategoryBusiness
Best used when
  • Mostly in legacy or infrastructure-heavy code where direct injection is impractical.
Tradeoffs
  • Can hide dependencies and make testing harder than dependency injection.
  • Often less desirable in modern code than explicit wiring.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

public final class ServiceRegistry {
    private final Map<Class<?>, Object> services = new HashMap<>();

    public <T> void register(Class<T> type, T instance) {
        services.put(type, instance);
    }

    public <T> T get(Class<T> type) {
        return type.cast(services.get(type));
    }
}

Related pages

Keep exploring