Search code examples
javadesign-patternsservice-locator

Is this valid implementation of ServiceLocator pattern in java?


I have an existential doubt. I saw an implementation of ServiceLocator pattern in C++ in some blog (Service Locator). So, I'm trying to extend the same implementation on Java SE (without any other auxiliar framework). See below the code.

My question: Is that a valid implementation for the ServiceLocator pattern in java?. If not is the case, what could be the most simple (example) implementation for this pattern in java?

/**
 * Where MyService1 and MyService2 are interfaces.
 */
public final class MyServiceLocator {

private static MyService1 service1;

private static MyService2 service2;

private MyServiceLocator() {
    // No op
}

public static MyService1 getMyService1() {
    if (service1 == null) {
        throw new NullMyService1Exception();
    }
    return service1;
}

public static MyService2 getMyService2() {
    if (service2 == null) {
        throw new NullMyService2Exception();
    }
    return service2;
}

public static void provideService1(MyService1 service1) {
    // Initialize Service1
    ...
    MyServiceLocator.service1 = service1;
}

public static void provideService2(MyService2 service2) {
    // Initialize Service2
    ...
    MyServiceLocator .service2 = service2;
}

}


Solution

  • Basically I see no problem with your implementation according to Service-Locator pattern, other than absence of caching strategy & using single access methods rather than having unique getters/setters for each service as explained in some sources. This might be a more clear example.

    But it looks like a terrible pattern. What is the need of that? As your source suggests, it's a way to contain a set of worker classes (which are implementing a common interface), and expose to clients without using Singletons.

    I don't see this as a good solution at all in terms of extend-ability. What will happens when you have to add to more services?? You have to

    • add more and more methods (in your way)
    • reproduce all the if-else ladders used to locate any service (as explained in the source I put)

    which looks quite terrible.

    If you have a set of services which are exposing same functionality to clients(i.e. implementing same interface), the best ways to expose them preserving the common behavior is either of

    patterns.