Service Locator Pattern


Service Locator Mode

Service Locator Pattern is used when we want to use JNDI queries to locate various services. Considering the high cost of finding JNDI for a service, the Service Locator pattern takes advantage of caching technology. When a service is first requested, the service locator looks up the service in JNDI and caches the service object. When the same service is requested again, the service locator looks in its cache, which can greatly improve the performance of the application. The following are the entities of this design pattern.

  • Service - The service that actually processes the request. A reference to this service can be found in the JNDI server.
  • Context / Initial Context - The JNDI Context has a reference to the service you are looking for.
  • Service Locator - The Service Locator is a single point of contact for services through the JNDI lookup and caching service.
  • Cache - Cache references to storage services to reuse them.
  • Client - Client is the object that invokes the service through ServiceLocator.

Implementation

We will create ServiceLocator, InitialContext, Cache, Service as various objects representing entities. Service1 and Service2 represent entity services.

ServiceLocatorPatternDemo, our demo class is here as a client that will use ServiceLocator to demonstrate the service locator design pattern.

UML diagram of service locator mode

Step 1

Create a service interface Service.

Service.java

public interface Service { public String getName(); public void execute(); }

Step 2

Create an entity service.

Service1.java

public class Service1 implements Service { public void execute(){ System.out.println("Executing Service1"); } @Override public String getName() { return "Service1"; } }

Service2.java

public class Service2 implements Service { public void execute(){ System.out.println("Executing Service2"); } @Override public String getName() { return "Service2"; } }

Step 3

Create an InitialContext for a JNDI query.

InitialContext.java

public class InitialContext { public Object lookup(String jndiName){ if(jndiName.equalsIgnoreCase("SERVICE1")){ System.out.println("Looking up and creating a new Service1 object"); return new Service1(); }else if (jndiName.equalsIgnoreCase("SERVICE2")){ System.out.println("Looking up and creating a new Service2 object"); return new Service2(); } return null; } }

Step 4

Create a cache Cache.






javacodegeeks is optimized for learning.© javacodegeeks .
All Right Reserved and you agree to have read and accepted our term and condition